Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to efficiently remove the same-length elements from a list in python

Tags:

python

For example, I have a list:

[[1,3],[23,4],[13,45,6],[8,3],[44,33,12]]

Is there any efficient way that I can finally get the list below?

[[1,3],[13,45,6]]

For every length of the list, keep only one element.

like image 551
Ding Ding Avatar asked Mar 11 '14 16:03

Ding Ding


2 Answers

Just make a dictionary keyed off the length and get its values:

>>> l = [[1,3],[23,4],[13,45,6],[8,3],[44,33,12]]
>>> dict((len(i), i) for i in l).values()
[[8, 3], [44, 33, 12]]
like image 144
Ben Avatar answered Sep 25 '22 20:09

Ben


s = set() [e for e in l if len(e) not in s and s.add(len(e)) is None]

like image 45
acushner Avatar answered Sep 23 '22 20:09

acushner