python - 在列表中搜索确切的字符串
问题描述
我正在做一个练习,我需要从列表中搜索确切的函数名称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])
请向我建议如何搜索确切的单词并仅获取该信息。
解决方案
对于每个有趣的函数,您只需遍历 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
推荐阅读
- laravel-5 - 在 Debian 上部署 laravel 项目的步骤是什么?
- terraform - Terraform EKS 标记
- flutter - 用未来的返回值声明变量
- typescript - Typescript - Generic for deriving the same type but with no properties undefined
- python-3.x - 如何使用 pandas 制作无界时间间隔索引?
- mysql - 如何强制终止任何正在运行的 mysql 查询?
- excel - 我当前使用的工作表是否有通用代码?
- android - 如何在 Flutter 中使用原生资源?
- python - 是否可以更改 tkinter 中菜单的字体?
- c - C中的垃圾值