Home > Software engineering >  Select items from two lists based on condition
Select items from two lists based on condition

Time:01-23

Hi I would like to scan through list x. And if the element has 1, I will pick the one preceding it plus the second value of element in y. Everything is in order, that is, the first element with 1 in x corresponds to the first element in y.

x = [['a', 3], ['b', 1], ['a', 1], ['b', 3], ['a', 4], ['b', 1], ['a', 1], ['b', 3], ['a', 2], ['b', 1]]

y = [['b', 9], ['a', 22], ['b', 10], ['a', 15], ['b', 20]]

I tried to paste my attempt but it keeps throwing indentation error. However, this is what I expect:

result = [['a', 3],9], [['b', 1],22], [['a', 4],10], [['b', 1],15], [['a', 2],20]]

Thank you very much!

CodePudding user response:

result = []
y_index = 0
for i in range(1, len(x)):
    if 1 in x[i]:
        result.append([x[i-1], y[y_index][1]])
        y_index =1
  • Related