奋斗的阿黄
2021-07-28 09:57
采纳率: 100%
浏览 46
已结题

python如何实现三个列表合并成为一个字典

list1 = [['A'], ['A'], ['A'], ['A'], ['A'], ['B'], ['B'], ['B'], ['B'], ['B'], ['C'], ['C'], ['C'], ['C'], ['C'], ['D'],
         ['D'], ['D'], ['D'], ['D']]
list2 = [['a'], ['b'], ['c'], ['d'], ['e'], ['a'], ['b'], ['c'], ['d'], ['e'], ['a'], ['b'], ['c'], ['d'], ['e'], ['a'],
         ['b'], ['c'], ['d'], ['e']]
list3 = [[3.0], [4.0], [0.0], [3.5], [0.0], [4.0], [0.0], [4.5], [0.0], [3.5], [0.0], [3.5], [0.0], [0.0], [3.0], [0.0],
         [4.0], [0.0], [3.5], [3.0]]

最后输出为

dict = {
            "A": {"a": 3.0, "b": 4.0, "c": 0.0, "d": 3.5, "e": 0.0},
            "B": {"a": 4.0, "b": 0.0, "c": 4.5, "d": 0.0, "e": 3.5},
            "C": {"a": 0.0, "b": 3.5, "c": 0.0, "d": 0.0, "e": 3.0},
            "D": {"a": 0.0, "b": 4.0, "c": 0.0, "d": 3.5, "e": 3.0},
}
  • 收藏

2条回答 默认 最新

  • 八云黧 2021-07-28 10:27
    已采纳

    本来想用字典解析试试能不能一行写出来,后来发现还是写for循环思路清晰
    直接用一个下标同时遍历三个列表,设计一个储存外层字典key(即遍历的上一个list1的元素值)的变量,当key发生改变说明需要在dict插入新的key,反之说明key已经存在,可以直接访问并修改已存在的内部字典

    dict= {}
    key = ''
    inner_dict={}
    for i in range(len(list1)):
        currrent_key = list1[i][0]
        inner_key = list2[i][0]
        inner_value = list3[i][0]
        if currrent_key != key :
            inner_dict = {inner_key:inner_value}
            dict[currrent_key] = inner_dict
        else:
            dict[currrent_key][inner_key] = inner_value
        key = currrent_key
    
    已采纳该答案
    打赏 评论
  • 阿牛烦死了 2021-07-28 10:08

    三层for循环嵌套编历每个列表

    打赏 评论

相关推荐 更多相似问题