[英]How to find the position in the list variable, searched by string [Python]
I have a list like我有一个像
result = ['Alice in the forest - 01.mp4', 'Code-009 - 02.mp4', 'Art 7 - 01.mp4', 'Will be owned - 05.mp4']
and a variable like this和这样的变量
search = 'Alice'
Is there a way to search through the list and find 'Alice in the forest - 01.mp4'
by keyword 'Alice'
and save the numbering of the variable in the list?有没有办法在列表中搜索并通过关键字
'Alice'
找到'Alice in the forest - 01.mp4'
并将变量的编号保存在列表中?
Ps: Until now, I was trying with string=re.compile("Alice")
. Ps:到目前为止,我一直在尝试使用
string=re.compile("Alice")
。 Didn't print out a thing though.虽然没有打印出来。
Thank you in advance.先感谢您。
To get all the strings that contain your search term, you can use:要获取包含搜索词的所有字符串,您可以使用:
match_string = [s for s in result if "Alice" in s]
To get the positions of all the strings that contain your search term, you can use:要获取包含搜索词的所有字符串的位置,您可以使用:
match_string = [i for i, s in enumerate(result) if "Alice" in s]
You need to iterate through list and find whether your search word occurs in the current item.您需要遍历列表并查找您的搜索词是否出现在当前项目中。
def searchWordInList(input_list, word):
index_and_value = []
for i in range(len(input_list)):
if word in input_list[i]:
index_and_value .append(i, input_list[i])
return index_and_value
result = ['Alice in the forest - 01.mp4', 'Code-009 - 02.mp4', 'Art 7 - 01.mp4', 'Will be owned - 05.mp4']
search = 'Alice'
index_and_value = searchWordInList(result, search)
You can also do it using the filter
and enumerate
function:您也可以使用
filter
和enumerate
函数来做到这一点:
result = ['Alice in the forest - 01.mp4', 'Code-009 - 02.mp4', 'Art 7 - 01.mp4', 'Will be owned - 05.mp4']
search = 'Alice'
output = list(filter(lambda song: search in song[1], enumerate(result)))
print(output)
Output:输出:
[(0, 'Alice in the forest - 01.mp4')]
import re
word1='Alice'
result = ['Alice in the forest - 01.mp4', 'Code-009 - 02.mp4', 'Art 7 - 01.mp4', 'Will be owned - 05.mp4']
for i, j in enumerate(result):
if word1 in j:
print i
enumerate() returns all index occurrences of "Alice' enumerate() 返回所有索引出现的“Alice”
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.