如果列表包含字符串,则打印列表中包含它的所有索引/元素

新手上路,请多包涵

我能够检测到匹配但无法找到它们在哪里。

给定以下列表:

 ['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"

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

我应该遍历列表中的每个索引并为每次迭代搜索“s 中的字符串”还是有更简单的方法来执行此操作?

原文由 user1552586 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 437
2 个回答

尝试这个:

 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 语句评估为真后中断

原文由 Brett Banks 发布,翻译遵循 CC BY-SA 3.0 许可协议

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 中。

原文由 Dan Getz 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题