我有一个很长的元组列表,大约有 4000 个条目。数据未排序。这不是完整的代码。这是一个简化的示例。如果可能的话,只是寻找一种加快速度的方法。
arr = [['863', '0.31', '0.00', '0.69'], ['621', '1.00', '0.00', '0.00'], ['834', '1.00', '0.00', '0.00']]
等等
我正在运行一个循环来比较具有 40000 个条目的文本文件,并且我需要在上面的数组中搜索匹配项。我用 numpy 数组想出的最好的方法:
nparr = np.asarray(arr)
lines = []
for i in range(40000):
ind = np.where(nparr == '834')
item = nparr[ind[0][0]]
lines.append(item[0])
写出结果
with open("output.txt", "w", buffering=8192) as file:
file.writelines(lines)
在我的 Windows 机器上,循环大约需要 1.3 秒,写出需要 0.02 秒。由于某种原因,在具有更好规格的 Linux 机器上,循环时间延长了 3 倍。我已将速度下降范围缩小到 np.where 函数。
有没有办法在没有 np.where 的情况下加快速度,或者我在这里处于最大速度?
谢谢
你的例子并没有什么意义,因为循环一遍又一遍地做同样的事情。
我假设在现实生活中
nparr == '834'
具有不同的值。
您可以测试所有值,而不是使用循环。首先根据所有文件构建一个
target
列表/数组,然后仅执行一次搜索。例如:
targets = ['834', '621']
m = np.isin(nparr, targets)
line = nparr[m.any(axis=1), 0]
输出:
['621', '834']
如果每行可以有多个匹配项:
idx = np.where(np.isin(nparr.ravel(), targets))[0]//nparr.shape[1]
line = nparr[idx, 0]