gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 13:37:23 25 4
gpt4 key购买 nike

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

test = [[0, 1], [0, 2], [1, 5], [1,6], [2, 0], [3, 99], [3, 89], [3, 79]]
test2 = [[1, 4], [4, 1]]

我想将它们转换为关联数组以便像这样快速查找:

test: {0: [1, 2], 1: [5,6], 2: [0], 3: [99, 98, 97]}
test2: {1: [4], 4: [1]}

我可以这样做:

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

last_val = i[0]
my_dict[last_val] = temp
return my_dict

但是,这不是很 Pythonic。有没有更 Pythonic 的方法来完成这个?

最佳答案

使用collections.defaultdict :

>>> test = [[0, 1], [0, 2], [1, 5], [1,6], [2, 0], [3, 99], [3, 89], [3, 79]]
>>>
>>> from collections import defaultdict
>>> d = defaultdict(list)
>>>
>>> for i, j in test:
... d[i].append(j)
...
>>> d
defaultdict(<type 'list'>, {0: [1, 2], 1: [5, 6], 2: [0], 3: [99, 89, 79]})

关于python - 如何将包含重复值的列表转换为以列表为值的字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37459042/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com