我能够检测到匹配但无法找到它们在哪里。
给定以下列表:
['A second goldfish is nice and all', 3456, 'test nice']
我需要搜索匹配项(即“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"
所以它找到了匹配项并打印了关键字和"is",但它没有告诉我它在哪里。
我应该遍历列表中的每个索引并为每次迭代搜索“string in s”还是有更简单的方法来做到这一点?
最佳答案
试试这个:
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 之后中断
关于python - 如果列表包含字符串,则打印列表中包含它的所有索引/元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21151174/