Python groupby()统计连续元素重复次数

groupby()可对list中的元素进行分组,并统计连续相同元素出现的次数
(*非连续的元素重新分组、统计)

import itertools
a = ['a', 'b', 'b', 'c', 'd', 'd', 'd', 'a', 'a']
items, counts = [], []
for k, v in itertools.groupby(a):
   items.append(k)
   counts.append(len(list(v)))
print 'items:', items
print 'counts:', counts
>>>
items: ['a', 'b', 'c', 'd', 'a']
counts: [1, 2, 1, 3, 2]

你可能感兴趣的:(Python groupby()统计连续元素重复次数)