简体   繁体   English

在Python列表中删除具有相同条目的压缩对

[英]Remove zipped pairs with same entries in Python list

I have a list of zipped pairs (for example A) 我有一个拉链对的列表(例如A)

A = [(0, 0), (0, 1), (0, 6), (0, 7), (1, 3), (1, 1), (2, 2)]

What's the best way in which I can remove all pairs where the first and the second entries equal each other (and create a new list)? 删除第一对和第二对相等的所有对(并创建新列表)的最佳方式是什么?

In the above example ( A ), the pairs that I wish to remove are (0, 0) , (1, 1) and (2, 2) . 在上面的示例( A )中,我希望删除的对是(0,0)(1,1)(2,2) In this example, I wish the new list to look like this. 在此示例中,我希望新列表看起来像这样。

A_new = [(0, 1), (0, 6), (0, 7), (1, 3)]

You can use simple list comprehension with if clause that returns True for all unequal pairs that you want to keep: 您可以对if子句使用简单的列表推导,对于要保留的所有不相等对,返回True

>>> A = [(0, 0), (0, 1), (0, 6), (0, 7), (1, 3), (1, 1), (2, 2)]
>>> [(x, y) for x, y in A if x != y]
[(0, 1), (0, 6), (0, 7), (1, 3)]

使用filter ,它将判断函数作为第一个参数来告知要保留的元素,并将可迭代列表作为第二个参数, lambda定义了一个匿名函数。

A_new = filter(lambda x: x[0] != x[1], A)

you can do it with list comprehension : 您可以使用list comprehension来做到这一点:

a = [(0, 0), (0, 1), (0, 6), (0, 7), (1, 3), (1, 1), (2, 2)]
final = [k for k in a if k[0] != k[1]]

Output: 输出:

print(final)
>>> [(0, 1), (0, 6), (0, 7), (1, 3)]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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