如何在以下列表中搜索包含字符串“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:
当前回答
我需要与以下匹配项对应的列表索引:
lst=['abc-123', 'def-456', 'ghi-789', 'abc-456']
[n for n, x in enumerate(lst) if 'abc' in x]
输出
[0, 3]
其他回答
要检查列表中任何字符串中是否存在“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]
这是一个很老的问题,但我提供了这个答案,因为前面的答案不处理列表中不是字符串(或某种可迭代对象)的项目。这些项目将导致整个列表理解失败,只有一个例外。
要通过跳过不可迭代的项来优雅地处理列表中的此类项,请使用以下命令:
[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中,如何确定对象是否可迭代?
def find_dog(new_ls):
splt = new_ls.split()
if 'dog' in splt:
print("True")
else:
print('False')
find_dog("Is there a dog here?")
x = 'aaa'
L = ['aaa-12', 'bbbaaa', 'cccaa']
res = [y for y in L if x in y]
any('abc' in item for item in mylist)