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

문제

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']
도움이 되었습니까?

해결책

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

다른 팁

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']]
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top