Remove sublist duplicates including reversed

后端 未结 7 1647
眼角桃花
眼角桃花 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:56

    You could iterate over the elements of the list, and use a set to keep track of those that have been seen so far. Using a set is a more convenient way to check for membership, since the operation has a lower complexity, and in that case you'll need to work with tuples, since lists aren't hashable. Then just keep those items if neither the actual tuple or the reversed have been seen (if you just want to ignore those which have a reversed you just need if tuple(reversed(t)) in s):

    s = set()
    out = []
    for i in l:
        t = tuple(i)
        if t in s or tuple(reversed(t)) in s:
            continue
        s.add(t)
        out.append(i)
    

    print(out)
    # [['1', '2'], ['1', '3'], ['1', '4'], ['1', '5'], ['2', '6']]
    

提交回复
热议问题