如何在列表变量中找到由字符串搜索的位置[Python]

时间:2018-11-23 09:01:40

标签: python list beautifulsoup qregularexpression

我有一个类似

的列表
  it('add button click', () => {
        const mockFn = jest.fn()
        wrapper.setMethods({
            changeView: mockFn
        })
        wrapper.find(ElementUI.Button).trigger('click');
        wrapper.update();
        expect(mockFn).toBeCalledWith(-1,'edit');
   })

和这样的变量

result = ['Alice in the forest - 01.mp4', 'Code-009 - 02.mp4', 'Art 7 - 01.mp4', 'Will be owned - 05.mp4']

是否可以搜索列表并通过关键字search = 'Alice' 找到'Alice in the forest - 01.mp4'并将变量编号保存在列表中?

P.s:到目前为止,我一直在尝试'Alice'。虽然没有打印出任何东西。

谢谢。

4 个答案:

答案 0 :(得分:2)

要获取包含搜索词的所有字符串,可以使用:

match_string = [s for s in result if "Alice" in s]

要获取包含搜索词的所有字符串的位置,可以使用:

match_string = [i for i, s in enumerate(result) if "Alice" in s]

答案 1 :(得分:0)

您需要遍历列表并查找您的搜索词是否出现在当前项目中。

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)

答案 2 :(得分:0)

您也可以使用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')]

答案 3 :(得分:0)

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”的所有索引出现