比较python中的两个坐标列表并使用坐标值赋值

2024-04-26 15:14:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两组数据来自两个独立的导入文件,这两个文件都被导入到python中,并且当前被放置在如下列表中。

清单1的格式如下:

(reference number, x coordinate, y coordinate)

Example list 1: [[1, 0, 0], [2, 0, 10], [3, 0, 20], [4, 0, 30], [5, 0, 40]]

清单2的格式如下:

(x coordinate, y coordinate, temperature)

Example list 2: [[0, 0, 100], [0, 10, 110], [0, 20, 120], [0, 30, 130], [0, 40, 140]]

我需要使用x和y坐标比较这两个列表,如果找到匹配项,生成一个包含相应参考号和温度的新列表。

例如,从上面的两个列表中,输出列表的格式如下:

(reference number, temperature)

Example Output list: [[1, 100], [2, 110], [3, 120], [4, 130], [5, 140]]

这是用大量的数据完成的,我真的很难找到解决方案,任何帮助都会非常感谢。干杯


Tags: 文件数据numbercoordinate列表outputexample格式
3条回答
lst1 = [[1, 0, 0], [2, 0, 10], [3, 0, 20], [4, 0, 30], [5, 0, 40]]
lst2 = [[0, 0, 100], [0, 10, 110], [0, 20, 120], [0, 30, 130], [0, 40, 140]]
dict1 = {(x, y): ref for ref, x, y in lst1}
dict2 = {(x, y): temp for x, y, temp in lst2}
matchxy = set(dict1) & set(dict2)
lstout = sorted([dict1[xy], dict2[xy]] for xy in matchxy)
print(lstout)

这将提供所需的输出

[[1, 100], [2, 110], [3, 120], [4, 130], [5, 140]]

我用集合来找出共同点。

这是可行的,但很容易阅读和理解。

 result = []
 for reference, x, y in list1:
     for a, b, temperature in list2:
         if x == a and y == b:
             result.append([temperature, reference])

通过迭代列表并将坐标存储在dict中,可以将复杂性降低到0(n),如下所示:

 dict1 = {}
 for reference, x, y in list1:
     dict[(x, y)] = reference

 dict2 = {}
 for x, y, temperature in list2:
     dict2[(x, y)] = temperature

 result = []
 for coordinate, reference in dict1.iteritems():
     temperature = dict2.get(coordinate)
     if temperature:
         result.append([temperature, reference])

您可以使用map-reduce执行此任务。

伪代码:

map1(list): #runs on first file
  for each (i,x,y) in list:
     emit ((x,y),(1,i))
map2(list): #runs on 2nd file
  for each (x,y,temp) in list:
     emit ((x,y),(2,temp))
reduce((x,y),list): #runs on output of both mappers
  for each (aux, val) in list:
       if aux == 1:
            i = val
       else:
            temp = val
  if both i and temp initialized:
       emit(i,temp)

Map Reduce是一个框架,如果将大数据问题建模为一系列Map Reduce任务,则可以轻松实现这些问题,上面的伪代码解释了Map Reduce步骤可能是什么。

这种方法可以很容易地处理大量的数据(包括peta规模),并让框架为您做不干净的工作。


其思想是首先将每个文件映射到某种哈希表中(这是由框架内部完成的),您有两个哈希表:

  1. 键=(x,y)值=id
  2. 键=(x,y)值=温度

一旦你有了两个哈希表,就很容易找到哪个id在一次传递中连接到哪个温度,并且一旦建立了连接-输出它。

这段代码的复杂度是O(n)一般情况。


请注意,如果坐标不是整数(但使用浮点),则需要使用基于树的映射而不是哈希表,并且在比较键时要非常小心,这是因为浮点运算的本质。
处理整数时不应出现此问题。

相关问题 更多 >