# Counting consecutive numbers in a list and pick corresponding numbers at the same index from another list

## Question:

I want to count if consecutive numbers are the same in the first list. If the count is 1, I want to pick the corresponding number in the second list.

``````lst1 = [[500],[500], [500], [300], [500], [300], [300], [200]]
lst2 = [[10], [10.5], [10.7], [9], [10.1], [97], [10.2], [10.9]]

def trains(lst):
element = []
freque = []
if not lst:
return element
count = 1
for i in range(len(lst)-1):
if lst[i][0] == lst[i+1][0]:
count += 1
else:
freque.append(count)
element.append(lst[i][0])
count = 1
freque.append(count)
element.append(lst[i+1][0])

return element,freque

print(trains(lst1)) # = ([500, 300, 500, 300, 200], [3, 1, 1, 2, 1])
``````

Eventually, I want the result to look like this:

``````[[300, 9], [500, 10.1], [200, 10.9]]
``````

Here is a fixed version of your code:

``````lst1 = [[500],[500], [500], [300], [500], [300], [300], [200]]
lst2 = [[10], [10.5], [10.7], [9], [10.1], [97], [10.2], [10.9]]

def trains(lst1, lst2):
result = []
count = 1
for i in range(1, len(lst1)):
if lst1[i][0] == lst1[i-1][0]:
count += 1
else:
if count == 1:
result.append([lst1[i-1][0], lst2[i-1][0]])
count = 1

if count == 1:
result.append([lst1[-1][0], lst2[-1][0]])
return result

print(trains(lst1, lst2))
``````

``````[[300, 9], [500, 10.1], [200, 10.9]]
``````

You can also use `itertools.zip_longest`:

``````from itertools import zip_longest

zippy = zip_longest(lst1, lst1[1:], lst1[2:], lst2, lst2[1:], lst[2:])
out = [[i1[0], j1[0]] for i0, i1, i2, j0, j1, j2 in zippy if (i1 != i0) & (i1 != i2)]
print(out)

# Output
[[300, 9], [500, 10.1], [200, 10.9]]
``````

Two input lists can be pairwised (`zip`), the obtained pairs are then grouped by the adjacent 1st value and filtered by "non-repeated" groups.
With `itertools.chain` and `itertools.groupby` operations:

``````from itertools import chain, groupby

gen_groups = (list(gr) for _, gr in
groupby(zip(chain.from_iterable(lst1), chain.from_iterable(lst2)), lambda x: x[0]))
res = [list(gr[0]) for gr in gen_groups if len(gr) == 1]
print(res)
``````

``````[[300, 9], [500, 10.1], [200, 10.9]]
``````
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.