Search code examples
pythonlistcompression

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


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]] 

Solution

  • 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]]