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]]
CodePudding user response:
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]]
CodePudding user response:
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]]