简体   繁体   English

Python:如果嵌套列表的第二项等于另一个列表的嵌套列表的第二项,则获取嵌套列表的第一项

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

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. 如何获取列表a和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. 列表a中每个嵌套列表的第二项与列表b嵌套列表的第二项相同,但第三项除外。

how to get the following output: 如何获得以下输出:

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

Use zip : 使用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: 使用zip和元组解包:

>>> 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 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM