Apply function per group of values of a key in list of dicts

為{幸葍}努か 提交于 2021-02-11 13:52:42

问题


Let's suppose I have this:

my_list = [{'id':'1','value':'1'},
{'id':'1','value':'8'},
{'id':'2','value':'2'},
{'id':'2','value':'3'},
{'id':'2','value':'5'},
]

and I want to apply a function (eg shuffle) for each group of values separately for the key id.

So I would like to have this for example:

my_list = [{'id':'1','value':'1'},
{'id':'1','value':'8'},
{'id':'2','value':'3'},
{'id':'2','value':'5'},
{'id':'2','value':'2'},
]

Therefore I do not want something to change between the different groups of values (eg id=1,2 etc) but only within each one separately.


回答1:


Use groupby directly in case your list is sorted by 'id' or sort by 'id' and use groupby:

from itertools import groupby
import random

my_list = [{'id':'1','value':'1'},
           {'id':'1','value':'8'},
           {'id':'2','value':'2'},
           {'id':'2','value':'3'},
           {'id':'2','value':'5'}]

res = []
for k, g in groupby(my_list, lambda x: x['id']):
    lst = list(g)
    random.shuffle(lst)
    res += lst

print(res)
# [{'id':'1','value':'1'},
#  {'id':'1','value':'8'},
#  {'id':'2','value':'3'},
#  {'id':'2','value':'5'},
#  {'id':'2','value':'2'}]


来源:https://stackoverflow.com/questions/59847407/apply-function-per-group-of-values-of-a-key-in-list-of-dicts

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!