Possible Duplicate:
Return the first item in a list matching a condition
How to easily grab the “matching” list element using list comprehension? e.g. I’ve a list and I’m looking for a element that starts with a a certain string. That’s easy to do:
>>> lines = ['AHP Buildlife number', 'NIT-Version-Default-v0.16.0', 'E_release v2.3.14.0']
>>> [ x.strip() for x in lines if x.startswith('NIT-Version-Default') ]
['NIT-Version-Default-v0.16.0']
But how can I do the same from in a if statement so that the matching list-element can be used for further processing; some thing like this:
>>> if [ x.strip() for x in lines if x.startswith('NSS-Checkin-Default') ]:
... ver = x.split('-')[-1].strip()
... print ver
So, that it return v0.16.0 as the version number. This obviously doesn’t work but hopefully you get the idea what I’m trying to do. Any idea how to do that? Cheers!!
PS. You are welcome to improve the question or the title.
If you’re looking for only one element:
Note that I’ve used a generator expression
(a for b in c if d), instead a list comprehension[a for b in c if d]. This way the iteration overlineswill only be done for as long as actually needed (in this case, until the first element is found).If no element is found,
nextwill raiseStopIteration.If you additionally want to make sure that there’s exactly one element (or exactly N elements for some fixed N), you could write it this way (assign to a tuple):
In that case you’ll have a
ValueErrorif the generator expression will yield too few or too many elements. This is called “tuple unpacking”.See also:
What is the best way to get the first item from an iterable matching a condition?