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

标签 python string list loops search

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

给定以下列表:

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

相关文章:

python - 如何停止对字符串列表中重复字母的过度计数

python - 将三个列表合并到一个字典中

java - 拆分字符串行列表并将单词添加到新列表中

python - 如何从数据框单元格中的格式项中删除重复项?

python - 用Python制作一个电子邮件函数

python - django-oauth2-提供者 : get the token without sending the client_secret

python - 如何解决python中的错误 'list assignment index out of range'

python - 如何将写节点附加到读节点?

javascript - 快速查找两个字符串是否具有共同字符的方法

python - 在 Python 3 中将字节列表转换为字符串