我的当前列表:
my_list = [
{'id': 1, 'val': [6]},
{'id': 2, 'val': [7]},
{'id': 3, 'val': [8]},
{'id': 2, 'val': [9]},
{'id': 1, 'val': [10]},
]
期望输出:
my_list = [
{'id': 1, 'val': [6, 10]},
{'id': 2, 'val': [7, 9]},
{'id': 3, 'val': [8]},
]
我尝试过以下几点:
my_new_list = []
id_set = set()
for d in my_list:
if d['id'] not in id_set:
id_set.add(d['id'])
temp = {'id': d['id'], 'val': d['val']}
my_new_list.append(temp)
else:
# loop over the new list and find the dict which already have d['id'] and update by appending value
# but this is not efficient
有没有更高效的方法或者我不知道的一些内置函数。
提示:顺序很重要!
id
值是唯一的,您可以使用字典来代替列表,并以id
作为键。这样,您就不必循环遍历新列表,而是可以直接通过id
访问它。 - spectras