myList = [2, 2, 2, 2, 1, 1, 0, 0, 0, 0, 1, 3, 2, 0, 2, 2, 0, 0, 0, 0]
import itertools
print sum(1 for key, group in itertools.groupby(myList) if len(list(group)) > 1 and key)
可读形式:
print sum(1
for key, group in itertools.groupby(myList)
if len(list(group)) > 1 and key)
输出
3
编辑:如果你不想使用上面看到的方法,
myList = [2, 2, 2, 2, 1, 1, 0, 0, 0, 0, 1, 3, 2, 0, 2, 2, 0, 0, 0, 0]
previous, count, result = myList[0], 0, 0
for num in myList[1:]:
if num == 0: continue
if previous != num:
if count:
result += 1
previous = num
count = 0
else:
count += 1
if count: result += 1
print result
输出
3
编辑1:根据您在评论部分的要求,
myList = [2, 2, 2, 2, 1, 1, 0, 0, 0, 0, 1, 3, 2, 0, 2, 2, 0, 0, 0, 0]
import itertools
groupedItems = [list(group) for key, group in itertools.groupby(myList) if key]
groupedItemsSizes = [len(item) for item in groupedItems if len(item) > 1]
print len(groupedItemsSizes) # Number of repeating groups
print float(sum(groupedItemsSizes))/len(groupedItemsSizes) # Mean
输出
3
2.66666666667