将字典列表拆分为块

时间:2017-08-14 20:41:22

标签: python django list split

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

我怎样才能改变这一点:

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

我需要在主列表中创建三个列表。每种促销类型一个。 感谢

1 个答案:

答案 0 :(得分:1)

使用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}]]

您可以为sortedgroupby(最好是相同的)提供关键功能,以便按特定属性进行分组:

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)]
相关问题