Given a list:
my_list = ['abc', 'def', 'ghi']
I want to extract the element that contains 'ab' (of which there will only ever be one).
Rather than something a little convoluted like:
[i for i in my_list if 'ab' in i][0]
I'm looking for some way of applying something that does the equivalent of XPath contains()
, but for a list.
If you are concerned about iterating through the entire list:
In [50]: L = ['abc', 'def', 'ghi']
In [51]: next(itertools.dropwhile(lambda s: 'ab' not in s, L))
Out[51]: 'abc'
Don't forget to import itertools
You can use filter
>>> my_list = ['abc', 'def', 'ghi']
>>> filter(lambda x: 'ab' in x, my_list)
['abc']
>>>
You can also create a function which can call a list:
>>> from functools import partial
>>> my_ab_func = partial(filter, lambda x: 'ab' in x)
>>> my_ab_func(my_list)
['abc']
>>> my_list2 = ['dabd', 'no','yes', 'zyx']
>>> my_ab_func(my_list2)
['dabd']
>>>
Use ifilter
from itertools
, it returns iterator instead of list:
from itertools import ifilter
my_list = ['abc', 'def', 'ghi']
next(ifilter(lambda x: 'ab' in x, my_list))
Rather than something a little convoluted like:
[i for i in my_list if 'ab' in i][0]
List comprehension is very much idiomatic for Python. If your lists are small, what you have is probably sufficient with some additional error checking:
def lcontains(needle_s, haystack_l):
try: return [i for i in haystack_l if needle_s in i][0]
except IndexError: return None
# Example use:
lcontains('ab', my_list)
That being said, if your input lists (or more generally, iterables) are potentially large, you might consider using itertools
:
import itertools
try:
irange = xrange # Python 2
ifilter = itertools.ifilter
except NameError:
irange = range # Python 3
ifilter = filter
def oneornone(iterable):
try: return iterable.next()
except StopIteration: return None
icontains = lambda predicate_f, haystack_i: oneornone(ifilter(predicate_f, haystack_i))
# Example use:
result = icontains(lambda i: i % 3323 == 0, irange(2, 1000000000000, 5))
# Or, in your case:
result = icontains(lambda i: 'ab' in i, mylist)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.