python - 根据第一个元素组合嵌套列表
问题描述
所以我有三个列表:
lst1 = [('test1', 0.2), ('test7', 0.2)]
lst2 = [('test1', 5.2), ('test2', 11.1), ('test7', 0.2)]
lst3 = [('test1', 19.2), ('test2', 12.1), ('test7', 19.2), ('test9', 15.1)]
我想要做的是浏览列表并创建以下元组:
[(test1, 0.2, 5.2, 19.2), (test2, 0.0, 11.1, 12.1), (test7, 0.2, 0.2, 19.2), (test9, 0.0, 0.0, 15.1)]
我试图通过多种方法解决这个问题,但没有运气,欢迎任何帮助!
解决方案
如果你真的想使用test1
etc. 作为唯一键,你最好使用字典。
我推荐以下内容:itertools.chain
用于组合您想要迭代的列表,并使用您只需将项目附加到的默认字典。
import itertools as it
from collections import defaultdict
lst1 = [('test1', 0.2), ('test7', 0.2)]
lst2 = [('test1', 5.2), ('test2', 11.1), ('test7', 0.2)]
lst3 = [('test1', 19.2), ('test2', 12.1), ('test7', 19.2), ('test9', 15.1)]
mydict = defaultdict(list)
for key, value in it.chain(lst1, lst2, lst3):
mydict[key].append(value)
print(mydict)
> defaultdict(
<class 'list'>,
{'test1': [0.2, 5.2, 19.2],
'test7': [0.2, 0.2, 19.2],
'test2': [11.1, 12.1],
'test9': [15.1]}
)
推荐阅读
- dialog - Blazor 同步确认同步融合
- ios - 请帮助更好地了解崩溃。崩溃细节:在 iOS 14、Xcode 12 上使用 Core Data
- javascript - 如何播放 .m4s 文件。并将它们转换为 Discord Bot 的二进制流
- grails - grails dbm-update 有时会给出 groovy.lang.MissingMethodException
- ruby - 如何为排序添加默认值:在 query_type.rb
- prolog - 更改参数顺序时 Prolog 统一被破坏
- data-structures - 两个单独的嵌套 while 循环的时间复杂度
- android - Google Assistant 自定义操作/意图类似于用于移动应用程序的 Siri Kit
- c# - 当请求需要很长时间时,net core 控制台应用程序 C# HttpClient 挂起
- google-cloud-dataflow - 在 Dataflow SQL 中解析属性