1

I get a list like that [[3,5],[5,3],[5,4],[0,2],[1,4],[1,2]]

So I want to delete [5,4] and [1,2] because list has same first of number [5,3] and [1,4]

so I tried

  1. append the small list
  2. reverse the list
  3. remove the list

but I don't know how can access [5,4] and [1,2]

>>> a=[[3,5],[5,3],[5,4],[0,2],[1,4],[1,2]]
>>> a.reverse()
>>> a.remove()
Traceback (most recent call last):
  File "<input>", line 1, in <module>
TypeError: remove() takes exactly one argument (0 given)
>>> a.remove(5)
Traceback (most recent call last):
  File "<input>", line 1, in <module>
ValueError: list.remove(x): x not in list
wjandrea
  • 28,235
  • 9
  • 60
  • 81
John Doe
  • 23
  • 2
  • Try a.remove([5,4]). – MegaEmailman Jun 05 '19 at 13:35
  • 1
    So you just want to remove ```[5,3],[1,4]``` or you want to remove duplicate elements in general? – jukebox Jun 05 '19 at 13:35
  • try `a.remove([1,2])` and `a.remove([5,4])` because you need to specify exactly what element in the list you want to remove. – MEdwin Jun 05 '19 at 13:35
  • to renove second element of list `del a[1]` or you can use funcs `reomve` and `pop` https://stackoverflow.com/questions/11520492/difference-between-del-remove-and-pop-on-lists/11520540 – Alaa Aqeel Jun 05 '19 at 13:39
  • The title is a bit misleading. It sounds like you want `del a[1]`, but really you want to remove elements where `elem[0]` is a repeat. You can [edit] it if you want to clarify. – wjandrea Jun 05 '19 at 13:47

3 Answers3

3

Use set to keep track of what is visited and add an entry only if it's not already visited:

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

seen = set()
print([x for x in lst if not (x[0] in seen or seen.add(x[0]))])

# [[3, 5], [5, 3], [0, 2], [1, 4]]
Austin
  • 25,759
  • 4
  • 25
  • 48
  • Maybe a word about lists comprehensions? https://www.pythonforbeginners.com/basics/list-comprehensions-in-python – olinox14 Jun 05 '19 at 13:43
1

My answer is almost the same as Austin's.

a=[[3,5],[5,3],[5,4],[0,2],[1,4],[1,2]]
dct={}
for x,y in a:
    if x not in dct:
        dct[x]=y 
print(list(dct.items()))
Anonymous
  • 335
  • 1
  • 2
  • 17
  • The output is a list of tuples. For a list of lists, use `print([list(item) for item in dct.items()])` – wjandrea Jun 05 '19 at 13:51
0

use itertools.groupby

[list(v)[0] for _,v in itertools.groupby(l,key=lambda x: x[0]) ]

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

If you can use pandas groupby

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

df=pd.DataFrame(l).groupby(0).first().reset_index().values.tolist() 

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

Wants in order

sorted( df, key=lambda x : l.index(x))

[[3, 5], [5, 3], [0, 2], [1, 4]]
PIG
  • 599
  • 3
  • 13