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

apol96

所以我有三个清单:

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

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

阿尔格里布
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)]

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

从嵌套列表的子列表中提取第一个和最后一个元素

选择嵌套列表的第一个元素

Python:嵌套列表中的第一个元素

根据每个列表的第一个元素从列表中删除项目

组合多维数组的第一个元素

嵌套列表中的第一个元素的总和

嵌套列表根据第一个值组合值

通过python中的第一个元素重新组合子列表

在嵌套列表的第一个位置计数相同的元素

删除嵌套列表的每个子列表的第一个元素

当第一个元素匹配时,如何对嵌套列表进行排序?

如何根据第一个元素对嵌套列表进行分组?

如何在terraform的嵌套列表中切片第一个元素

仅当存在第一个元素时才获取列表的组合

根据第一个元素合并列表

如何拆分嵌套列表元素的第一个元素?

使用ruby根据数组的第一个元素组合数组值

将嵌套列表转换为dict,其中列表的第一个元素是dict的键

根据给定的第一个元素从列表列表中检索列表

如何在优先排序列表长度的同时,根据第一个元素从嵌套列表中删除重复项?

根据列表中的以下元素获取第一个元素的范围

将嵌套列表的第一个元素绑定到嵌套列表的后续元素

基于嵌套列表的第一个元素合并嵌套列表

计算嵌套列表中的第一个元素

根据列表的最后一个值和第一个值在 python 中附加嵌套列表

根据子列表的第一个元素拆分子列表列表

列表/嵌套列表中的第一个元素

如何访问嵌套列表的第一个元素?

如何通过嵌套列表中第一个元素的值提取子列表