Python 将字典列表拆分为块

Python 将字典列表拆分为块,python,django,list,split,Python,Django,List,Split,我有一个python列表,里面有两个列表(每个房间一个,有两个房间),里面有字典 我如何才能将其转换为: 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'), 'ro

我有一个python列表,里面有两个列表(每个房间一个,有两个房间),里面有字典

我如何才能将其转换为:

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'}]
]
为此:

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'}]
]
我需要在主列表中创建三个列表。每种类型的宣传片一份。 感谢使用,您可以使用以下内容:

>>> 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}]]
您可以为排序的
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)]

答案很好,我投了赞成票,但如果我理解正确,它只能按原样工作,因为
A
中的第二个子列表具有不同的房间和价格。如果那里有额外的物品,比如说3号房间和669.42的价格,它们就不会与其他具有相同价格的物品组合在一起。这可以通过
itertools.chain
ing
A
[k的列表(g),g在groupby中(排序(chain.from_iterable(A),key=fnc),key=fnc)]轻松解决。