在dict python列表中按键值属性分组

时间:2019-02-05 10:45:50

标签: python json list dictionary filter

我有orig个元组列表,其中包含dicttext个值。

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')]]

2 个答案:

答案 0 :(得分:1)

如果您使用SELECT * FROM myTable WHERE ( SELECT CONVERT(date, myDateTimeColumn) ) = '2019-01-01' ,会更容易。

SELECT * 
FROM myTable 
WHERE date(myDateTimeColumn) > '2019-01-01'
  AND
SELECT * 
FROM myTable 
WHERE date(myDateTimeColumn) < '2019-01-02'

输出:

numpy

答案 1 :(得分:1)

使用itertools.groupbylist 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')]]

我希望这很重要:)