Python: 使用多个条件在文件中搜索

Python: search in file with multiple criteria

我有一个包含多列的文本文件,如下所示:

1000 1 2 3
1000 1.5 2.5 3.1
2000 4 5 6
3000 7 8 9

我想创建一个 python 脚本,我在其中输入一系列 3 个数字,搜索前 3 列中最接近的数字和最后一列的 return 对应值。 例如,如果我输入 1200 1 2 它应该 return 3.

更新:是否可以在第二行和第三行具有相同值的数据之间进行线性插值? 例如我的数据是: 1000 100 2 0.1 1200 100 2 0.2 1000 80 3 0.4 我的输入是“1100 100 2”,它应该 return 0.15.

  1. 打开文件,

    values = []
    with open("myfile.txt") as inf:
    
  2. 阅读每一行,

        for line in inf:
    
  3. 转换成数字,

            values.append([float(s) for s in line.split()])
    
  4. 定义"closest"的意思。曼哈顿距离?最小二乘法?

    def make_manhattan_dist_fn(from):
        def distance_fn(pt):
            return sum(abs(b-a) for a,b in zip(from, pt))
        return distance_fn
    
    my_dist_fn = make_manhattan_dist_fn([1200, 1, 2])
    

    编辑:根据你的评论,你想要

    def make_tuple_dist_fn(from):
        def distance_fn(pt):
            return tuple(abs(b - a) for a,b in zip(from, pt))
        return distance_fn
    
    my_dist_fn = make_tuple_dist_fn([1200, 1, 2])
    
  5. 找到最接近的值,

    print(min(values, key = my_dist_fn)[-1])
    

    这导致

    3.0
    

也许是这样的?

from scipy.interpolate import griddata

input_data = [1100, 100, 4]
values = []

with open("prova.txt") as lista:

for line in lista:
    if line.find('RPM') == -1:
       values.append([float(s) for s in line.split()])

restricted = []
for i in range(len(values)):
    if values[i][2] == input_data[2]:
        restricted.append([values[i][0], values[i][1], values[i][3]])

points = []
valori = []

for i in range(len(restricted)):
    points.append( [restricted[i][0],restricted[i][1]] )
    valori.append( restricted[i][2] )


grid_x = input_data[0]
grid_y = input_data[1]

grid_z1 = griddata(points, valori, (grid_x, grid_y), method='linear')

"prova.txt" 是:
1200 100 4 0.1
1150 100 4 0.1
1050 100 4 0.2
1000 100 4 0.2
1200 90 4 0.1
1150 90 4 0.1
1050 90 4 0.2
1000 90 4 0.2
1100 100 2 0.3