![](/img/trans.png)
[英]Getting the item with the maximum value in list of dicts after grouping the dict by key
[英]Grouping by key value property in List of dict python
我有包含dict
和text
值的元组的orig
列表。
orig = [({'x': 28.346, 'y': 19},'Text0'),
({'x': 109.726, 'y': 19},'Text1'),
({'x': 147.776, 'y': 19},'Text2'),
({'x': 153.606, 'y': 24}, 'Text3'),
({'x': 452.788, 'y': 24}, 'Text4'),
({'x': 504.168, 'y': 34}, 'Text5'),
({'x': 527.768, 'y': 34}, 'Text6'),
({'x': 533.598, 'y': 45},'Text7'),
({'x': 64.291, 'y': 55},'Text8'),
({'x': 98.623, 'y': 55},'Text9')]
我想从key='y'
中过滤组,这将使我根据y
唯一值列出它。 类似于以下内容:
res = [
[({'x': 28.346, 'y': 19},'Text0'),
({'x': 109.726, 'y': 19},'Text1'),
({'x': 147.776, 'y': 19},'Text2')],
[({'x': 153.606, 'y': 24}, 'Text3'),
({'x': 452.788, 'y': 24}, 'Text4')],
[({'x': 504.168, 'y': 34}, 'Text5'),
({'x': 527.768, 'y': 34}, 'Text6')],
[({'x': 533.598, 'y': 45},'Text7')],
[({'x': 64.291, 'y': 55},'Text8'),
({'x': 98.623, 'y': 55},'Text9')]]
如果你使用numpy
它会更容易一些。
import numpy as np
orig = [({'x': 28.346, 'y': 19}, 'Text0'),
({'x': 109.726, 'y': 19}, 'Text1'),
({'x': 147.776, 'y': 19}, 'Text2'),
({'x': 153.606, 'y': 24}, 'Text3'),
({'x': 452.788, 'y': 24}, 'Text4'),
({'x': 504.168, 'y': 34}, 'Text5'),
({'x': 527.768, 'y': 34}, 'Text6'),
({'x': 533.598, 'y': 45}, 'Text7'),
({'x': 64.291, 'y': 55}, 'Text8'),
({'x': 98.623, 'y': 55}, 'Text9')]
input_array = np.array([val[0]['y'] for val in orig])
out_array = [np.where(input_array == element)[0].tolist() for element in np.unique(input_array)]
res = [[orig[i] for i in ind_arr] for ind_arr in out_array]
print(res)
输出:
[[({'x': 28.346, 'y': 19}, 'Text0'),
({'x': 109.726, 'y': 19}, 'Text1'),
({'x': 147.776, 'y': 19}, 'Text2')],
[({'x': 153.606, 'y': 24}, 'Text3'),
({'x': 452.788, 'y': 24}, 'Text4')],
[({'x': 504.168, 'y': 34}, 'Text5'),
({'x': 527.768, 'y': 34}, 'Text6')],
[({'x': 533.598, 'y': 45}, 'Text7')],
[({'x': 64.291, 'y': 55}, 'Text8'),
({'x': 98.623, 'y': 55}, 'Text9')]]
使用itertools.groupby
和list comprehension
两行解决方案:
from itertools import groupby
# group by the input orig with a key of dict "y" and then take it in a list of list comprehension
print ([[x for x in v] for k, v in groupby(orig, key= lambda x: x[0]["y"])])
结果:
[[({'x': 28.346, 'y': 19}, 'Text0'), ({'x': 109.726, 'y': 19}, 'Text1'), ({'x': 147.776, 'y': 19}, 'Text2')], [({'x': 153.606, 'y': 24}, 'Text3'), ({'x': 452.788, 'y': 24}, 'Text4')], [({'x': 504.168, 'y': 34}, 'Text5'), ({'x': 527.768, 'y': 34}, 'Text6')], [({'x': 533.598, 'y': 45}, 'Text7')], [({'x': 64.291, 'y': 55}, 'Text8'), ({'x': 98.623, 'y': 55}, 'Text9')]]
我希望这很重要:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.