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