python-3.x - 比较多维两个列表并填充零
问题描述
我有 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# 中那样工作。你能帮我解决这个问题吗?如果我写的代码不正确,你会写一个示例代码来实现我的目标吗?谢谢
解决方案
据我了解,您的数据应如下所示:
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]
推荐阅读
- html - 在 iOS / Safari 上并排显示元素的 CSS 失败
- objective-c - NSCollectionView 标头显示
- php - 在单个查询中使用多个 JOINS 进行更新
- apache-spark - 除了在 Pyspark 中运行 rdd.extract 之外,在运行 pyspark ML 算法后是否有任何有效的函数来提取概率向量?
- android - 进行新更改后构建对 apk 文件的反应本机应用程序?
- sonarqube - 我们能否用 SonarQube 替换静态应用程序安全测试 SAST 工具,例如(Fortify、Checkmarx 和 IBM Appscan)
- html - 在图片悬停时使段落出现在图片内
- java - 带有随机键的 JSON 到 Java 对象
- c++ - 无法使用 CC:Sun C++ 5.12 编译器在 Oracle Solaris 11.1 SPARC 上构建 poco-1.9.4-all 的 Crypto 模块
- angular - ASP.NET Core 中的属性绑定不将属性值绑定到视图模型