Python:if list contains string打印列表中包含i的所有索引/元素

2024-05-14 20:47:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我能探测到火柴,但找不到它们在哪里。

给出以下列表:

['A second goldfish is nice and all', 3456, 'test nice']

我需要搜索match(即“nice”)并打印包含它的所有列表元素。理想情况下,如果要搜索的关键字是“nice”,则结果应该是:

'A second goldfish is nice and all'
'test nice'

我有:

list = data_array
string = str(raw_input("Search keyword: "))
print string
if any(string in s for s in list):
    print "Yes"

所以它找到匹配项并同时打印,关键字和“是”,但它不告诉我它在哪里。

我应该遍历列表中的每个索引,并为每个迭代搜索“s中的字符串”还是有一种更简单的方法来完成?


Tags: andintest列表stringismatch关键字
3条回答

试试这个:

list = data_array
string = str(raw_input("Search keyword: "))
print string
for s in list:
    if string in str(s):
        print 'Yes'
        print list.index(s)

编辑为工作示例。如果只需要第一个匹配索引,也可以在If语句计算为true后中断

matches = [s for s in my_list if my_string in str(s)]

或者

matches = filter(lambda s: my_string in str(s), my_list)

请注意,'nice' in 3456将引发一个TypeError,这就是我在列表元素上使用str()的原因。这是否合适取决于您是否想考虑将'45'放入3456

print filter(lambda s: k in str(s), l)

相关问题 更多 >

    热门问题