gpt4 book ai didi

python - python 中的高效字符串比较,包括数值评估

转载 作者:太空宇宙 更新时间:2023-11-03 15:23:17 25 4
gpt4 key购买 nike

我有两个中等大小的 ascii 文件,其中包含固定格式的数据。我需要测试第一个文件一行中的 6 个给定字段是否与第二个文件任何一行中的六个字段匹配(在给定的公差范围内),然后输出一个公共(public)行以继续处理。

我目前正在使用 fortran 风格的行阅读器拆分文件中的每一行,并为每个列表中的每个元素生成一个具有正确类型的列表列表。我将两个文件的列表列表存储在内存中,同时对它们进行操作

我需要比较的字段都是 float ,我目前使用的是以下类型的流:

tol = 0.01
for entry1 in file1List:
for entry2 in file2List:
if (abs(entry1[1] - entry2[1]) < tol and abs(entry1[2] - entry2[2]) < tol
and abs(entry1[3] - entry2[3]) < tol and abs(entry1[4] - entry2[4]) < tol
and abs(entry1[5] - entry2[5]) < tol and abs(entry1[6] - entry2[6]) < tol):
print entry1,entry2

对于仅包含少量行的文件执行此操作没问题,但超过 30000 行时,仅执行此部分就超过 1 分钟!

我相当确定必须有一种更快的比较方法,但我正在努力寻找它,我们将不胜感激。

最佳答案

如果您可以将 file1listfile2list 中的元素存储为 numpy 数组,您的比较就会变得更简单(也可能更快):

for entry1 in file1list:
for entry2 in file2list:
if(np.all(np.abs(entry1[1:7] - entry2[1:7]) > tol)):
print entry1,entry2

转换为 numpy 数组很容易:

file1list = [ np.array(entry) for entry in file1list ]

对于已排序的 file2list

,这会变得更好一点
file2list=sorted(file2list,key=operator.itemgetter(1,2,3,4,5,6))
for entry1 in file1list:
for entry2 in file2list:
d=np.abs(entry1[1:7]-entry2[1:7])
if(np.all(d < tol)):
print entry1,entry2
elif(d[0] > tol):
break

关于python - python 中的高效字符串比较,包括数值评估,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11617782/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com