Python:如果列表包含字符串打印列表中包含它的所有索引/元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21151174/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python: if list contains string print all the indexes / elements in the list that contain it
提问by
I am able to detect matches but unable to locate where are they.
我能够检测到匹配,但无法定位它们在哪里。
Given the following list:
鉴于以下列表:
['A second goldfish is nice and all', 3456, 'test nice']
I need to search for match (i.e. "nice") and print all the list elements that contain it. Ideally if the keyword to search were "nice" the results should be:
我需要搜索匹配(即“不错”)并打印包含它的所有列表元素。理想情况下,如果要搜索的关键字“不错”,结果应该是:
'A second goldfish is nice and all'
'test nice'
I have:
我有:
list = data_array
string = str(raw_input("Search keyword: "))
print string
if any(string in s for s in list):
print "Yes"
So it finds the match and prints both, the keyword and "Yes" but it doesn't tell me where it is.
所以它找到匹配并打印关键字和“是”,但它没有告诉我它在哪里。
Should I iterate through every index in list and for each iteration search "string in s" or there is an easier way to do this?
我应该遍历列表中的每个索引以及每次迭代搜索“s 中的字符串”还是有更简单的方法来做到这一点?
采纳答案by Brett Banks
Try this:
尝试这个:
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)
Editted to working example. If you only want the first matching index you can also break after the if statement evaluates true
编辑为工作示例。如果你只想要第一个匹配的索引,你也可以在 if 语句评估为真后中断
回答by Dan Getz
matches = [s for s in my_list if my_string in str(s)]
or
或者
matches = filter(lambda s: my_string in str(s), my_list)
Note that 'nice' in 3456will raise a TypeError, which is why I used str()on the list elements. Whether that's appropriate depends on if you want to consider '45'to be in 3456or not.
请注意,这'nice' in 3456会引发 a TypeError,这就是我str()在列表元素上使用的原因。这是否合适取决于您是否想考虑'45'加入3456。
回答by bainikolaus
print filter(lambda s: k in str(s), l)

