2017-08-03 68 views
0

我有一組記錄,我想在兩個單獨的字段上組合在一起。每條記錄都是一個Python字典。其中一個字段是日期值,另一個是數字字段。 IE中:現在Python組記錄在一起字段

h = [{'date': 20170728, 'group': 121, ...}, 
    {'date': 20170729, 'group': 131, ...}, 
    ...] 

,如果我想組某些羣體一起,說任何組是在[123,134,145],但具有相同的日期,他們組合在一起,但每另一組被分組一起自己,我會怎麼做到這一點?

我用下面的代碼:

grouped_list = [] 
for date, items in groupby(h, key=itemgetter('date'): 
    g = list(items) 
    grouped_list.append(g) 

,我正在尋找的輸出如下:

grouped_list = [ 
       [records that have a distinct date value and group], 
       [records that have a distinct date but are in the group [123, 134, 145], 
       etc.] 

在組123,134的記錄,145不應該在grouped_list中有各自的列表。應該將它們組合在一個列表中。

+0

你能否提供輸出你」的例子重新找? – cowbert

+0

使用'grouped_records = sorted(h,key = lambda x:x ['date'])來排序列表'是否符合您的需求?或者你在找別的東西嗎? –

+0

請注意'collections.groupby'組連續迭代器。由於字典的迭代順序是不可預知的,所以這可能不是正確的方法 –

回答

0

您可以編寫一個自定義函數來計算鍵,以便將記錄的,是這樣的:

from itertools import groupby 

records = [ 
     {'date': 20170728, 'group': 121}, 
     {'date': 20170729, 'group': 131}, 
     {'date': 20170729, 'group': 134}, 
     {'date': 20170729, 'group': 145}, 
] 
grouped_groups = [123, 134, 145] 

def compute_groupby_key(entry): 
     return "%d-%d" % (
      entry['date'], 
      grouped_groups[0] if entry['group'] in grouped_groups else entry['group'] 
    ) 

grouped_records = [list(entries) for key, entries in groupby(records, compute_groupby_key)] 

這裏grouped_records包含:

[ 
    [{'date': 20170728, 'group': 121}], 
    [{'date': 20170729, 'group': 131}], 
    [{'date': 20170729, 'group': 134}, {'date': 20170729, 'group': 145}]] 
]