Reputation: 23
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
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
Reputation: 602
[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
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
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