我当前的列表:
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
任何其他更有效的方法或可能是一些内置的功能,我不知道。你知道吗
附言:秩序很重要!你知道吗
与ozgur方法相同,但使用
collections.defaultdict
:您可以使用^{} 按
'id'
对原始list
进行排序和分组,并为每个组累积'val'
:^{} 是您的朋友:
(我们应该使用
collections.OrderedDict
来记住第一次插入键的顺序。)相关问题 更多 >
编程相关推荐