假设我有两个由另一个函数生成的列表:
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)