![](/img/trans.png)
[英]How do I use a variable to find the position of an element in a list in Python?
[英]How to find the position in the list variable, searched by string [Python]
我有一个像
result = ['Alice in the forest - 01.mp4', 'Code-009 - 02.mp4', 'Art 7 - 01.mp4', 'Will be owned - 05.mp4']
和这样的变量
search = 'Alice'
有没有办法在列表中搜索并通过关键字'Alice'
找到'Alice in the forest - 01.mp4'
并将变量的编号保存在列表中?
Ps:到目前为止,我一直在尝试使用string=re.compile("Alice")
。 虽然没有打印出来。
先感谢您。
要获取包含搜索词的所有字符串,您可以使用:
match_string = [s for s in result if "Alice" in s]
要获取包含搜索词的所有字符串的位置,您可以使用:
match_string = [i for i, s in enumerate(result) if "Alice" in s]
您需要遍历列表并查找您的搜索词是否出现在当前项目中。
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)
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() 返回所有索引出现的“Alice”
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.