繁体   English   中英

如何在列表变量中找到位置,按字符串搜索[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)

您也可以使用filterenumerate函数来做到这一点:

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)

输出:

[(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() 返回所有索引出现的“Alice”

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM