Search code examples
python-3.xlist-comprehension

List comprehension for 3 lists


I need some help with list comprehension for 3 python lists. First, I want to check items in list b is they are consecutive. If not, then I will append the corresponding values in list a and c to a new list. If they are, then I will move on until I find a different number to append a and c values.

This is how I tried:

a = [40,0,40,40,0,40,0,0,0,40]
b = [1, 2, 3, 3,4,5,7,7,7,8]
c = [1.2,1.1,1.3,1.4, 1.5,1.0, 0.9, 1.6, 0.6, 0.8]


def lst(a, b, c):
    zeros = []
    count = 1
    for i in range(1, len(b)):
        if b[i] == b[i-1] & a[i] == a[i-1]:
            count += 1

        else:
            zeros.append([a[i-1], c[i-1]])

    return zeros

data = lst(a, b, c)

print(data)

Unfortunately it is including everything in the output except the last value

I am expecting to see data = [[40,1.2], [0,1.1], [40,1.3], [0,1.5], [40,1.1], [0,0.9], 40,0.8]]


Solution

  • Judging by your desired output, I guess you want to include elements at index where b is greater that at the previous index (consecutive would mean +=1):

    data = [[a[i], c[i]] for i in range(len(b)) if i==0 or b[i]>b[i-1]]
    

    Output:

    [[40, 1.2], [0, 1.1], [40, 1.3], [0, 1.5], [40, 1.0], [0, 0.9], [40, 0.8]]