首页 > 解决方案 > 根据第一个元素组合嵌套列表

问题描述

所以我有三个列表:

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)]

我试图通过多种方法解决这个问题,但没有运气,欢迎任何帮助!

标签: pythonloopstuplesnested-lists

解决方案


如果你真的想使用test1etc. 作为唯一键,你最好使用字典。

我推荐以下内容: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]}
)

推荐阅读