使用python将dict值分组为块
我试图找出一种方法,根据键的值,将字典值分组为区间 在我的例子中,我有两个键:“timestamp”和“value”;我需要根据值按间隔对其进行分组。我的数据结构如下:使用python将dict值分组为块,python,itertools,Python,Itertools,我试图找出一种方法,根据键的值,将字典值分组为区间 在我的例子中,我有两个键:“timestamp”和“value”;我需要根据值按间隔对其进行分组。我的数据结构如下: [{'timestamp': u'1389631816', 'value': u'0'}, {'timestamp': u'1389633136', 'value': u'0'}, {'timestamp': u'1389633256', 'value': u'1'}, {'timestamp': u'1389633316
[{'timestamp': u'1389631816', 'value': u'0'},
{'timestamp': u'1389633136', 'value': u'0'},
{'timestamp': u'1389633256', 'value': u'1'},
{'timestamp': u'1389633316', 'value': u'1'},
{'timestamp': u'1389633196', 'value': u'0'},
{'timestamp': u'1389633196', 'value': u'0'},
{'timestamp': u'1389633196', 'value': u'0'},
{'timestamp': u'1389633316', 'value': u'1'}]
在这种情况下,我应该有4个组:
First Group: 2 items, based on value '0';
Second Group: 2 items, based on value '1';
Third Group: 3 items, based on value '0';
Fourth Group: 1 item, based on value '1'.
出于所有目的,在本例中,我需要这些组从Zabbix进行ICMP检查的时间间隔指标来创建报告,但我真的被困在这里。使用该函数对这些组进行分组:
from itertools import groupby
from operator import itemgetter
for value, group in groupby(list_of_dicts, key=itemgetter('value')):
print 'Group for value {}'.format(value)
for d in group:
print d
演示:
使用该功能对以下各项进行分组:
from itertools import groupby
from operator import itemgetter
for value, group in groupby(list_of_dicts, key=itemgetter('value')):
print 'Group for value {}'.format(value)
for d in group:
print d
演示:
itemgetter的使用非常有趣。代码易于理解,完全符合Python语言。非常感谢您非常有趣地使用itemgetter。代码易于理解,完全符合Python语言。非常感谢。