Pythonic way of removing reversed duplicates in list

后端 未结 9 2409
难免孤独
难免孤独 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:22

    If the order of pairs and pair-items matters, creating a new list by testing for membership might be the way to go here.

    pairs = [0, 1], [0, 4], [1, 0], [1, 4], [4, 0], [4, 1]
    no_dups = []
    for pair in pairs:
        if not any( all( i in p for i in pair ) for p in no_dups ):
            no_dups.append(pair)
    

    Otherwise, I'd go with Styvane's answer.

    Incidentally, the above solution will not work for cases in which you have matching pairs. For example, [0,0] would not be added to the list. For that, you'd need to add an additional check:

    for pair in pairs:
        if not any( all( i in p for i in pair ) for p in no_dups ) or ( len(set(pair)) == 1 and not pair in no_dups ):
            no_dups.append(pair)
    

    However, that solution will not pick up empty "pairs" (eg, []). For that, you'll need one more adjustment:

        if not any( all( i in p for i in pair ) for p in no_dups ) or ( len(set(pair)) in (0,1) and not pair in no_dups ):
            no_dups.append(pair)
    

    The and not pair in no_dups bit is required to prevent adding the [0,0] or [] to no_dups twice.

提交回复
热议问题