Pythonic way of removing reversed duplicates in list

后端 未结 9 2386
难免孤独
难免孤独 2020-12-06 09:49

I have a list of pairs:

[0, 1], [0, 4], [1, 0], [1, 4], [4, 0], [4, 1]

and I want to remove any duplicates where

[a,b] == [         


        
9条回答
  •  一生所求
    2020-12-06 10:06

    Well, I am "checking for the reverse pair and append to a list if that's not the case" as you said you could do, but I'm using a single loop.

    x=[[0, 1], [0, 4], [1, 0], [1, 4], [4, 0], [4, 1]]
    out = []
    for pair in x:
        if pair[::-1] not in out:
            out.append(pair)
    print out
    

    The advantage over existing answers is being, IMO, more readable. No deep knowledge of the standard library is needed here. And no keeping track of anything complex. The only concept that might be unfamiliar for beginners it that [::-1] reverts the pair.

    The performance is O(n**2) though, so do not use if performance is an issue and/or lists are big.

提交回复
热议问题