小编Jon*_*gro的帖子

如何将包含重复值的列表转换为以列表作为值的字典?

假设我有两个由另一个函数生成的列表:

test = [[0, 1], [0, 2], [1, 5], [1,6], [2, 0], [3, 99], [3, 89], [3, 79]]
test2 = [[1, 4], [4, 1]]
Run Code Online (Sandbox Code Playgroud)

我想将它们转换为关联数组,以便快速查找,如下所示:

test: {0: [1, 2], 1: [5,6], 2: [0], 3: [99, 98, 97]}
test2: {1: [4], 4: [1]}
Run Code Online (Sandbox Code Playgroud)

我可以这样做:

def list_to_dict(my_list):
    last_val = my_list[0][0]
    temp = []
    my_dict = {}

    for i in my_list:
        if last_val == i[0]:
            temp.append(i[1])
        else:
            #add the values to this key
            my_dict[last_val] = temp
            #reset the list
            temp = []
            temp.append(i[1]) …
Run Code Online (Sandbox Code Playgroud)

python list-comprehension

3
推荐指数
1
解决办法
38
查看次数

标签 统计

list-comprehension ×1

python ×1