Removing Duplicates from Nested List Based on First 2 Elements

后端 未结 3 1003
一整个雨季
一整个雨季 2020-12-19 12:11

I\'m trying to remove duplicates from a nested list only if the first 2 elements are the same, ignoring the third...

List:

L = [[\'el1\',\'el2\',\'va         


        
3条回答
  •  粉色の甜心
    2020-12-19 12:29

    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()
    

    Or on Python 2.7 and higher:

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

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

提交回复
热议问题