根据第一个元素合并嵌套列表

4

所以我有三个列表:

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

我已经尝试了多种方法,但都没有成功,欢迎提供任何帮助!

包含你目前编写的代码也会很有帮助。此外,你的问题类似于合并多个字典合并Python字典,只不过你有一个键值对列表而不是字典中的键和值。 - algrebe
2个回答

3
如果您真的想使用“test1”等作为唯一键,最好使用字典。
我建议如下操作:使用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]}
)

这不是我真正想要的输出,我该怎么做才能让输出变成: {'test1': [0.2, 5.2, 19.2], 'test7': [0.2, 0.2, 19.2], 'test2': [0.0, 11.1, 12.1], 'test9': [0.0, 0.0, 15.1]} - apol96
你如何决定哪些列表在第一个元素上额外添加 0.0,而哪些不需要呢? - Daniel Lenz

2
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)]
# create a list containing all these lists
lst_of_lists = [lst1, lst2, lst3]
# Create a dictionary where keys are the test1, test2, test3...
# and the values are [0.0, 0.0, ....] as many as the number of lists
output_dict = {
    name:[0.0]*len(lst_of_lists) for lst in lst_of_lists
    for (name, value) in lst
}

# Now, 'test1' in lst1 has to modify output_dict['test1'][0]
#      'test1' in lst2 modifies output_dict['test1'][1]
# and so on...
for idx, lst in enumerate(lst_of_lists):
    for key, value in lst:
        output_dict[key][idx] = value

# this gives you a dictionary
print("output_dict: ", output_dict)

# you can convert it back to a list with .items(), and since you want it sorted
print("dict_as_list: ", sorted(output_dict.items()))

# since you want the keys and values together in the same tuple
output_list = [tuple([key] + val_list) for key, val_list in output_dict.items()]
# and sort that
output_list = sorted(output_list)
print("output_list: ", output_list)

输出:

output_dict:  {'test1': [0.2, 5.2, 19.2], 'test7': [0.2, 0.2, 19.2], 'test2': [0.0, 11.1, 12.1], 'test9': [0.0, 0.0, 15.1]}
dict_as_list:  [('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])]
output_list:  [('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)]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接