python 给定一组参考距离值时出现最小距离的打印时间

rta7y2nd  于 2023-06-20  发布在  Python
关注(0)|答案(1)|浏览(108)

从列表A中的值列表,我想知道列表B的时间(第一列),其中与列表A的值的最小距离出现(第二列中报告的距离)。

import numpy

list_A = np.loadtxt('listA.dat')
file_B = np.loadtxt('listB.dat')

distances = file_B[:,1]
time = file_B[:,0]

abs_differences = []

for point in list_A:
    diffs = []
    for distance in distances:
        diffs.append(abs(distance-point))
        list={}
        list=['Point'] = point
        list=['AbsDiff'] = diffs
        abs_differences.append(list)

for ele in abs_differences:
   diffs = ele['AbsDiff']
   index = diffs.index(min(diffs))
   with open("output.txt","a") as f:
       print(time[index], file=f)

然而,输出文件需要很长的时间来写入,因为对于列表B的每个点出现最小距离的时间是针对数据集的每个点打印的,因此具有多次出现的时间值。有没有一种方法可以解决这个问题,比如简化代码?

b4wnujal

b4wnujal1#

你在类型之间切换了几次,并且使用了python关键字 list 作为变量名,所以你的代码不能正常工作,至少有这两个原因。
您应该尝试基于以下简化代码的操作:

import numpy as np

list_A = np.loadtxt('listA.dat')
file_B = np.loadtxt('listB.dat')

list_B = file_B[:,1]
times = file_B[:,0]

min_times = []  # list of tuples (pointA, pointB, indexB, distance, time)
for pointA in list_A:
    min_distance = float('inf')
    min_time = None
    
    for indexB, pointB in enumerate(list_B):
        distance = abs(pointA - pointB)
        if distance < min_distance:
            min_distance = distance
            min_time = times[indexB]
    min_times.append((pointA, pointB, indexB, min_distance, min_time))
    

print(min_times)

# if you want the distances: (index 3 in the tuple)
print([mt[3] for mt in min_times])

# you can also write to file once you are sure of the result wanted

相关问题