Python: getting first item of a nested list if its second item equals a nested list's second item of another list

StackOverflow https://stackoverflow.com/questions/20897579

  •  23-09-2022
  •  | 
  •  

Pregunta

I have the following lists:

a = [['a', 'x'], ['b', 'y'], ['c', 'z']]
b = [['d', 'x'], ['e', 'y'], ['f', 'm']]

How to get the first items of all nested lists of list a and b. The second items of each nested lists in list a are equal to the second items of the nested lists of list b with the exception of the third ones.

how to get the following output:

['a', 'd']
['b', 'e']
¿Fue útil?

Solución

Use zip:

>>> a = [['a', 'x'], ['b', 'y'], ['c', 'z']]
>>> b = [['d', 'x'], ['e', 'y'], ['f', 'm']]
>>> [[x[0], y[0]] for x, y in zip(a, b) if x[1]==y[1]]
[['a', 'd'], ['b', 'e']]

Otros consejos

Another way could be:

r = [[a[i][0], b[i][0]] for i in range(len(a)) if a[i][1] == b[i][1]]
print r

Output:

[['a', 'd'], ['b', 'e']]

Using zip and tuple unpacking:

>>> a = [['a', 'x'], ['b', 'y'], ['c', 'z']]
>>> b = [['d', 'x'], ['e', 'y'], ['f', 'm']]
>>> [[a1, b1] for (a1, a2), (b1, b2) in zip(a, b) if a2 == b2]
[['a', 'd'], ['b', 'e']]
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top