且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

基于前两个元素从嵌套列表中删除重复项

更新时间:2023-02-22 12:39:18

如果顺序无关紧要,则可以使用相同的方法,但是将第一和第二个元素的元组用作键:

If the order doesn't matter, you can use that same method but using a tuple of the first and second elements as the key:

dict(((x[0], x[1]), x) for x in L).values()

或者在Python 2.7和更高版本上:

Or on Python 2.7 and higher:

{(x[0], x[1]): x for x in L}.values()

您可以使用tuple(x[:2])代替(x[0], x[1]),只要您认为可读性更高即可.

Instead of (x[0], x[1]) you can use tuple(x[:2]), use whichever you find more readable.