Removing the lists from a list which are duplicated for some items

后端 未结 4 1559
面向向阳花
面向向阳花 2020-12-20 00:32

I\'m trying to remove the lists from a list which have same first and third items but only keeping the first one. Example list and output:

li=[ [2,4,5], [1,3         


        
4条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-20 01:10

    This is a solution based on @iurisilvio's iterator comment and which uses itertools.compress in conjunction with the set-based solutions from the others. Instead of building up an output_list from elements in the input list, a selector list comprising Boolean values is built up on a one:one basis with respect to elements from the input list. A value of True indicates that the corresponding element from the input list should be retained in the output. The selector can then be applied on the input list via itertools.compress to product an output iterable.

    from itertools import compress
    li=[ [2,4,5], [1,3,5], [1,6,5] ]
    b_li = set()
    selectors = []
    for x in li:
        s = (x[0], x[2])
        if s not in b_li:
            b_li.add(s)
            selectors.append(True)
        else:
            selectors.append(False)
    
    for x in compress(li, selectors):
      print x
    [2, 4, 5]
    [1, 3, 5]
    

提交回复
热议问题