如何在以下列表中搜索包含字符串'abc'
的项目?
xs = ['abc-123', 'def-456', 'ghi-789', 'abc-456']
以下代码检查列表中是否存在'abc'
,但无法检测到'abc-123'
和'abc-456'
:if 'abc' in xs:
如何在以下列表中搜索包含字符串'abc'
的项目?
xs = ['abc-123', 'def-456', 'ghi-789', 'abc-456']
以下代码检查列表中是否存在'abc'
,但无法检测到'abc-123'
和'abc-456'
:if 'abc' in xs:
要在列表中的任何字符串中检查是否存在 'abc'
:
xs = ['abc-123', 'def-456', 'ghi-789', 'abc-456']
if any("abc" in s for s in xs):
...
获取所有包含 'abc'
的项:
matching = [s for s in xs if "abc" in s]
filter(lambda element: 'abc' in element, some_list)
。 - floer32any("abc" in s for s in some_list)
放在另一个函数中,并说 contains("abc",list)
。 - Tarikindex()
方法:try: return mylist.index(myitem); except ValueError: pass
。 - Sven Marnach"abc" in some_string
会检查 some_string
中是否存在完全一致、连续的子字符串 "abc"
,所以 "abc" in "cba-4123"
和 "abc" in "a-b-c"
都将返回 False
。不需要对代码进行修改。 - Sven Marnach我只是想提出一个想法:如果你需要匹配多个字符串,例如abc
和def
,你可以将两个推导式组合如下:
matchers = ['abc','def']
matching = [s for s in my_list if any(xs in s for xs in matchers)]
输出:
['abc-123', 'def-456', 'abc-456']
{s for s in my_list for xs in matchers if xs in s}
(注意使用花括号来创建唯一的集合)。这种写法可能更易于阅读,但如果大多数s
值都有匹配项,则速度可能会较慢,因为你的any
函数会在第一个匹配项处高效停止。 - Matthias Frippmatching = [s for s in my_list if all(xs in s for xs in matchers)]
- Dan使用filter
过滤得到所有包含'abc'
的元素:
>>> xs = ['abc-123', 'def-456', 'ghi-789', 'abc-456']
>>> list(filter(lambda x: 'abc' in x, xs))
['abc-123', 'abc-456']
你也可以使用列表推导式:
>>> [x for x in xs if 'abc' in x]
如果你只需要知道'abc'是否在其中一个项目中,这是最短的方法:
if 'abc' in str(my_list):
注意:这假设“abc”是一个包含字母和数字的文本。如果“abc”可能只是特殊字符(例如[]'),请不要使用它。
虽然这是一个比较旧的问题,但我提供这个答案是因为之前的答案无法处理列表中不是字符串或某种可迭代对象的项。这些项会导致整个列表推导式出现异常。
为了优雅地处理这样的列表项并跳过非可迭代项,请使用以下代码:
[el for el in lst if isinstance(el, collections.Iterable) and (st in el)]
接下来,拿到这样一个列表:
lst = [None, 'abc-123', 'def-456', 'ghi-789', 'abc-456', 123]
st = 'abc'
你仍将得到匹配的项目 (['abc-123', 'abc-456']
)
这个可迭代性的测试可能不是最好的。从这里获取:在Python中,如何确定对象是否可迭代?
[el for el in lst if el and (st in el)]
不是更有意义吗? - Gordomy_list = ['abc-123', 'def-456', 'ghi-789', 'abc-456']
不需要过于复杂化。 - Gordox = 'aaa'
L = ['aaa-12', 'bbbaaa', 'cccaa']
res = [y for y in L if x in y]
for item in my_list:
if item.find("abc") != -1:
print item
if 'abc' in item
而不是使用item.find('abc') == -1
。 - Wyatt Baldwinany('abc' in item for item in mylist)
我是Python的新手。我让下面的代码运行起来并使它易于理解:
my_list = ['abc-123', 'def-456', 'ghi-789', 'abc-456']
for item in my_list:
if 'abc' in item:
print(item)
__contains__()
方法。a = ['abc-123', 'def-456', 'ghi-789', 'abc-456']
for i in a:
if i.__contains__("abc") :
print(i, " is containing")