John Doe
John Doe

Reputation: 23

How can I delete second element of list

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

Upvotes: 1

Views: 239

Answers (3)

PIG
PIG

Reputation: 602

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]]

Upvotes: 0

Anonymous
Anonymous

Reputation: 355

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()))

Upvotes: 1

Austin
Austin

Reputation: 26039

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]]

Upvotes: 3

Related Questions