Raphi
Raphi

Reputation: 420

Sorted by type in Python

Say I have a list of objects. Maybe its got some ints, some strings, and some floats. What I'd like to do is sort the list so that all ints are moved to the end of the list but no other types are touches, sort of like this...

for idx, el in enumerate(somelist):
    if el.__class__ is int:
        somelist.append(somelist.pop(idx))

My question is, is there a way to do this elegantly as a one-liner?

Upvotes: 1

Views: 492

Answers (4)

gilwo
gilwo

Reputation: 1671

maybe this will be useful in another way:

>>> a=[4,'3','2', 6,7,4,'ssa']
>>> for i,j in groupby(sorted(a, key=lambda x: str(type(x))), type):
...     tuple(j)
...
(4, 6, 7, 4)
('3', '2', 'ssa')
>>>

Upvotes: 1

Padraic Cunningham
Padraic Cunningham

Reputation: 180411

isinstance(x,int) will be True or False so ints will get moved to the end:

l = [1.0,"foo",2,3,"bar"]
print(sorted(l, key=lambda x: isinstance(x,int)))
[1.0, 'foo', 'bar', 2, 3]

Upvotes: 3

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798686

Boolean values are orderable in Python. And sorting is stable.

..., key=lambda x: isinstance(x, int), ...

Upvotes: 4

Amber
Amber

Reputation: 526633

If you don't care about doing it in place...

newlist = [i for i in somelist if not isinstance(x, int)] + [i for i in somelist if isinstance(x, int)]

Conveniently, since Python 2.2, sorts are stable, so you can also just do...

somelist.sort(key=lambda x: isinstance(x, int))

Note however that this does meant that any subclass of int will also be moved to the end of the list - if you don't want that, you'd want to change the condition to type(x) is int).

Upvotes: 2

Related Questions