Python – removing dupes in list of lists

  • A+
Category:Languages

Basically, what I'm trying to do is remove any lists that begin with the same value. For example two of the below begin with the number 1:

a = [[1,2],[1,0],[2,4],[3,5]] 

because the value 1 exists at the start of two of the lists -- I need to remove both so that the new list becomes:

b = [[2,4],[3,5]] 

can someone please help me with this?

i've tried the below but the output is: [[1, 2], [2, 4], [3, 5]]

def unique_by_first_n(n, coll):     seen = set()     for item in coll:         compare = tuple(item[:n])          print compare   # Keep only the first `n` elements in the set         if compare not in seen:             seen.add(compare)             yield item  a = [[1,2],[1,0],[2,4],[3,5]]  filtered_list = list(unique_by_first_n(1, a)) 

 


You can use collections.Counter with list comprehension to get sublists whose first item appears only once:

from collections import Counter c = Counter(n for n, _ in a) b = [[x, y] for x, y in a if c[x] == 1] 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: