简体   繁体   English

在Python中提取一个包含字符串的列表项,而无需列表理解?

[英]Extract a list item in Python that contains a string, without list comprehension?

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). 我想提取包含“ ab”的元素(其中将永远只有一个)。

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. 我在寻找某种方法来应用与XPath contains()等效的方法,但要使用列表。

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 不要忘记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: 使用itertools ifilter ,它返回迭代器而不是列表:

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. 列表理解对于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 : 话虽这么说,如果您的输入列表(或更一般而言,可迭代对象)可能很大,则可以考虑使用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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM