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?
CodePudding user response:
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
CodePudding user response:
As mentioned in the comments, your code is resetting the count to 0 as it loops through each inner list.
Given that you have already created the tem_list
- you can get the pairs with simply [len(t) - 1 for t in tem_list]