Remove sublist duplicates including reversed

后端 未结 7 1631
眼角桃花
眼角桃花 2020-12-07 04:27

For example i have following

list = [[\'1\', \'2\'], [\'1\', \'3\'], [\'1\', \'4\'], [\'1\', \'5\'], [\'2\', \'1\'], [\'4\', \'1\'], [\'2\', \'6\']]
         


        
7条回答
  •  春和景丽
    2020-12-07 04:42

    This is similar to solution by @Mehul Gupta, but I think their solution is traversing the list twice if matched: one for checking and one for removing. Instead, we could

    the_list = [['1', '2'], ['1', '3'], ['1', '4'], ['1', '5'], ['2', '1'], ['4', '1'], ['2', '6']]
    for sub_list in the_list:
        try:
            idx = the_list.index(sub_list[::-1])
        except ValueError:
            continue
        else:
            the_list.pop(idx)
    
    print(the_list)
    # [['1', '2'], ['1', '3'], ['1', '4'], ['1', '5'], ['2', '6']]
    

    because it is easier to ask for forgiveness than permission.

    Note: Removing elements whilst looping is not a good thing but for this specific problem, it does no harm. In fact, it is better because we do not check the mirrored again; we already removed it.

提交回复
热议问题