首页 > 解决方案 > 在列表中搜索确切的字符串

问题描述

我正在做一个练习,我需要从列表中搜索确切的函数名称fun并从另一个列表中获取相应的信息detail

这是动态列表detail

csvCpReportContents =[
['[PLT] rand (DEBUG INFO NOT FOUND)', '11', '15'],
['rand', '10', '11', '12'],
['__random_r', '23', '45'],
['__random', '10', '11', '12'],
[],
['multiply_matrices()','23','45'] ]

这是fun包含要搜索的函数名称的列表:

fun = ['multiply_matrices()','__random_r','__random']

函数的预期输出fun[2]

 ['__random', '10', '11', '12']

函数的预期输出fun[1]

['__random_r', '23', '45'],

这是我尝试过的fun[2]

for i in range(0, len(csvCpReportContents)):
    row = csvCpReportContents[i]
    if len(row)!=0:
        search1 = re.search("\\b" + str(fun[2]).strip() + "\\b", str(row))
        if search1:
            print(csvCpReportContents[i])

请向我建议如何搜索确切的单词并仅获取该信息。

标签: pythonregexstringmatch

解决方案


对于每个有趣的函数,您只需遍历 csv 列表,检查第一个元素是否以它开头

csvCpReportContents = [
    ['[PLT] rand (DEBUG INFO NOT FOUND)', '11', '15'],
    ['rand', '10', '11', '12'],
    [],
    ['multiply_matrices()', '23', '45']]

fun=['multiply_matrices()','[PLT] rand','rand']

for f in fun:
    for c in csvCpReportContents:
        if len(c) and c[0].startswith(f):
            print(f'fun function {f} is in csv row {c}')

输出

fun function multiply_matrices() is in csv row ['multiply_matrices()', '23', '45']
fun function [PLT] rand is in csv row ['[PLT] rand (DEBUG INFO NOT FOUND)', '11', '15']
fun function rand is in csv row ['rand', '10', '11', '12']

更新了代码,因为您更改了问题中的测试用例和要求。我的第一个答案是基于您想要匹配以 item from fun 开头的行的测试用例。现在您似乎已经更改了该要求以匹配完全匹配,如果不完全匹配匹配,则以匹配开头。下面的代码已更新以处理该场景。但是我会说下次你的问题要清楚,不要在几个人回答后改变标准

csvCpReportContents =[
['[PLT] rand (DEBUG INFO NOT FOUND)', '11', '15'],
['rand', '10', '11', '12'],
['__random_r', '23', '45'],
['__random', '10', '11', '12'],
[],
['multiply_matrices()','23','45'] ]

fun = ['multiply_matrices()','__random_r','__random','asd']

for f in fun:
    result = []
    for c in csvCpReportContents:
        if len(c):
            if f == c[0]:
                result = c
            elif not result and c[0].startswith(f):
                result = c

    if result:
        print(f'fun function {f} is in csv row {result}')
    else:
        print(f'fun function {f} is not vound in csv')

输出

fun function multiply_matrices() is in csv row ['multiply_matrices()', '23', '45']
fun function __random_r is in csv row ['__random_r', '23', '45']
fun function __random is in csv row ['__random', '10', '11', '12']
fun function asd is not vound in csv

推荐阅读