kan lile
kan lile

Reputation: 31

appending values to a list from list

 l1= [[1,2],[3,4],[5,6],[1,2]]
 l2= [[4,9],[2,9],[2,2],[6,3]]

I want to append second value of list 2 to list 1 if first value of l2 matches last value of l1.

new l1= [[1,2,9],[3,4,9],[5,6,3],[1,2,2]]

Upvotes: 2

Views: 55

Answers (2)

Shawn Zhang
Shawn Zhang

Reputation: 1884

[x+(y[1:]) for x,y in zip(l1,l2) if x[1] == y[0]]

Upvotes: 2

Marcin
Marcin

Reputation: 238887

You can do it as follows:

l1= [[1,2],[3,4],[5,6]]
l2= [[2,4],[4,9],[2,2]]

newL = [v1 + [v2[1]] for v1,v2 in zip(l1,l2) if v2[0] == v1[1]]

print(newL) # [[1, 2, 4], [3, 4, 9]]

Upvotes: 2

Related Questions