如何在以下列表中搜索包含字符串“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:
当前回答
any('abc' in item for item in mylist)
其他回答
mylist=['abc','def','ghi','abc']
pattern=re.compile(r'abc')
pattern.findall(mylist)
只是抛出这个:如果你恰好需要匹配多个字符串,例如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']
any('abc' in item for item in mylist)
x = 'aaa'
L = ['aaa-12', 'bbbaaa', 'cccaa']
res = [y for y in L if x in y]
要检查列表中任何字符串中是否存在“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]