首页 > 解决方案 > 比较多维两个列表并填充零

问题描述

我有 2 个列表,如下所示。

list1 = [(271.086, 350.919 , 309.912, 384.286),
         (575.991, 240.076, 644.586, 302.432)]

list2 = [(2.0, 235.0, 17.0, 257.0),
         (21.0, 218.0, 44.0, 247.0),
         (52.0, 264.0, 78.0, 284.0),
         (80.0, 235.0, 100.0, 251.0),
         (173.0, 190.0, 198.0, 211.0),
         (184.0, 174.0, 205.0, 190.0),
         (192.0, 154.0, 211.0, 176.0),
         (254.0, 154.0, 275.0, 182.0),
         (273.0, 348.0, 307.0, 381.0),
         (536.0, 297.0, 617.0, 371.0),
         (573.0, 235.0, 649.0, 300.0)]

我想将 list1 等同于 list2。我将零分配给那些在 List1 中没有 list2 等价物的人。最后:

list1 = [(0, 0, 0, 0),
         (0, 0, 0, 0),
         (0, 0, 0, 0),
         (0, 0, 0, 0),
         (0, 0, 0, 0),
         (0, 0, 0, 0),
         (0, 0, 0, 0),
         (0, 0, 0, 0),
         (271.086, 350.919 , 309.912, 384.286),
         (0, 0, 0, 0),
         (575.991, 240.076, 644.586, 302.432))]

我写了下面的代码来做到这一点。但这给了我第 2 行(如果阻塞)的错误“列表索引超出范围”。

for i in range (len(list2)):
    if (abs(list2[i][0] - list1[i][0]) == list2[i][0]) 
    and (abs(list2[i][1] - list1[i][1]) == list2[i][1])
    and (abs(list2[i][2] - list1[i][2]) == list2[i][2])
    and (abs(list2[i][3] - list1[i][3]) == list2[i][3])

       list1[i].insert(0,[0,0,0,0])
   else :
       list1[i] = list1[i]

我知道 pyhton for 循环不像在 C# 中那样工作。你能帮我解决这个问题吗?如果我写的代码不正确,你会写一个示例代码来实现我的目标吗?谢谢

标签: python-3.xlistfor-loop

解决方案


据我了解,您的数据应如下所示:

list1 = [(271.086, 350.919 , 309.912, 384.286),
         (575.991, 240.076, 644.586, 302.432)]

list2 = [(2.0, 235.0, 17.0, 257.0),
         (21.0, 218.0, 44.0, 247.0),
         (52.0, 264.0, 78.0, 284.0),
         (80.0, 235.0, 100.0, 251.0),
         (173.0, 190.0, 198.0, 211.0),
         (184.0, 174.0, 205.0, 190.0),
         (192.0, 154.0, 211.0, 176.0),
         (254.0, 154.0, 275.0, 182.0),
         (271.086, 350.919 , 309.912, 384.286),
         (536.0, 297.0, 617.0, 371.0),
         (575.991, 240.076, 644.586, 302.432)]

要获得预期的结果,您可以使用for循环:

default = (0,0,0,0)
result = []
for e in list2:
    if e in list1:
        result.append(e)
    else:
        result.append(default)
result

输出:

[(0, 0, 0, 0),
 (0, 0, 0, 0),
 (0, 0, 0, 0),
 (0, 0, 0, 0),
 (0, 0, 0, 0),
 (0, 0, 0, 0),
 (0, 0, 0, 0),
 (0, 0, 0, 0),
 (271.086, 350.919, 309.912, 384.286),
 (0, 0, 0, 0),
 (575.991, 240.076, 644.586, 302.432)]

或者您可以使用列表理解:

[e if e in list1 else (0,0,0,0) for e in list2]

推荐阅读