如何在以下列表中搜索包含字符串“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的信息
a = ['abc-123', 'def-456', 'ghi-789', 'abc-456']
aa = [ string for string in a if "abc" in string]
print(aa)
Output => ['abc-123', 'abc-456']
其他回答
如果您只需要知道“abc”是否在其中一项中,这是最短的方法:
if 'abc' in str(my_list):
注意:这假设“abc”是字母数字文本。如果“abc”可能只是一个特殊字符(即[]”,),请不要使用它。
使用筛选器获取具有“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]
这是一个很老的问题,但我提供了这个答案,因为前面的答案不处理列表中不是字符串(或某种可迭代对象)的项目。这些项目将导致整个列表理解失败,只有一个例外。
要通过跳过不可迭代的项来优雅地处理列表中的此类项,请使用以下命令:
[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中,如何确定对象是否可迭代?
我是Python新手。我得到了下面的代码,使其易于理解:
my_list = ['abc-123', 'def-456', 'ghi-789', 'abc-456']
for item in my_list:
if 'abc' in item:
print(item)
只是抛出这个:如果你恰好需要匹配多个字符串,例如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']