[英]Split list of dictionaries into chunks
I have a python list with two list inside(one for each room - there are 2 rooms), with dictionaries inside. 我有一个python列表,里面有两个列表(每个房间一个-有2个房间),里面有字典。
How can i transform this: 我该如何转换:
A = [
[{'rate': Decimal('669.42000'), 'room': 2L, 'name': u'10% OFF'},
{'rate': Decimal('669.42000'), 'room': 2L, 'name': u'10% OFF'},
{'rate': Decimal('632.23000'), 'room': 2L, 'name': u'15% OFF'},
{'rate': Decimal('632.23000'), 'room': 2L, 'name': u'15% OFF'}],
[{'rate': Decimal('855.36900'), 'room': 3L, 'name': u'10% OFF'},
{'rate': Decimal('855.36900'), 'room': 3L, 'name': u'10% OFF'}]
]
Into This: 变成这个:
A = [
[{'rate': Decimal('669.42000'), 'room': 2L, 'name': u'10% OFF'},
{'rate': Decimal('669.42000'), 'room': 2L, 'name': u'10% OFF'}],
[{'rate': Decimal('632.23000'), 'room': 2L, 'name': u'15% OFF'},
{'rate': Decimal('632.23000'), 'room': 2L, 'name': u'15% OFF'}],
[{'rate': Decimal('855.36900'), 'room': 3L, 'name': u'10% OFF'},
{'rate': Decimal('855.36900'), 'room': 3L, 'name': u'10% OFF'}]
]
I need to create in the main list, three lists inside. 我需要在主列表中创建三个列表。 one for each type of promo.
每种促销都有一个。 Thanks
谢谢
Using itertools.groupby
, you could use this nested comprehension: 使用
itertools.groupby
,您可以使用以下嵌套的理解:
>>> from itertools import groupby
>>> from pprint import pprint
>>> x = [list(g) for l in A for k, g in groupby(sorted(l))]
>>> pprint(x)
[[{'name': u'10% OFF', 'rate': Decimal('669.42000'), 'room': 2L},
{'name': u'10% OFF', 'rate': Decimal('669.42000'), 'room': 2L}],
[{'name': u'15% OFF', 'rate': Decimal('632.23000'), 'room': 2L},
{'name': u'15% OFF', 'rate': Decimal('632.23000'), 'room': 2L}],
[{'name': u'10% OFF', 'rate': Decimal('855.36900'), 'room': 3L},
{'name': u'10% OFF', 'rate': Decimal('855.36900'), 'room': 3L}]]
You can provide a key function to both sorted
and groupby
(preferably the same) in order to group by a specific property: 您可以为
sorted
和groupby
(最好是相同的)提供键功能,以便按特定属性进行分组:
from operator import itemgetter
fnc = itemgetter('rate') # if you want to group by rate
x = [list(g) for l in A for k, g in groupby(sorted(l, key=fnc), key=fnc)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.