To count how many consecutive pairs of number in a list, here’s an example:
[150,151,152,262]
There are 2 consecutive pairs, which are 150 & 151, 151 & 152.
I try below:
import more_itertools as mit
import itertools
iterable = [150,151,152,262]
tem_list = [list(group) for group in mit.consecutive_groups(iterable)]
# [[150, 151, 152], [262]]
i = 0
for t in tem_list:
if len(t) == 1:
i = 0
if len(t) == 2:
i += 1
if len(t) == 3:
i += 2
print (i)
But it doesn’t work. What went wrong, and how can I correct it?
>Solution :
Using a grouping function for this is overkill. You can use zip() to pair each item with its successor and add the result of comparing them using the sum function:
L = [150,151,152,262]
C = sum(a+1==b for a,b in zip(L,L[1:]))
print(C) # 2