Reputation: 818
I am trying to sort a list of numbers depending on whether it is odd or even (even gains higher priority). Example:
a=[1,2,3,4]
a.sort(key=org(a)) sorted will produce [2,4,1,3]. I want to use the sort method
def org(a):
for i in range(len(a)):
if a[i]%2==0:
b.append(a[i])
b.sort()
else:
c.append(a[i])
c.sort()
print(b+c)
I got this error from running a.sort(key=org(a))
Traceback (most recent call last):
File "<pyshell#80>", line 1, in <module>
a.sort(key=org(a))
TypeError: 'list' object is not callable
I realize that sorting it every time makes it slow. Which other way can I do this without having to sort after every loop?
Upvotes: 2
Views: 2396
Reputation: 304137
To sort by "evenness" and then by magnitude, you can use a function that returns a tuple
>>> a=[1,2,3,4]
>>> a.sort(key=lambda x: (x % 2, x))
>>> a
[2, 4, 1, 3]
To sort the odd entries first, you can simply negate the value of the modulus. This is a useful trick for reversing the sort of numeric fields in general.
>>> a.sort(key=lambda x:(-(x % 2), x))
>>> a
[1, 3, 2, 4]
Upvotes: 7
Reputation: 5658
one can use helper function from intertools
def partition_by_pred(pred, iterable):
from itertools import tee, filterfalse
t1, t2 = tee(iterable)
return filterfalse(pred, t1), filter(pred, t2)
l, r = partition_by_pred(lambda x: False if x % 2 == 0 else True ,[1,2,3,4] )
print(*l,*r)
2 4 1 3
Upvotes: 0
Reputation: 5115
It looks like you were on the right track:
a = [1,2,3,4]
>>> sorted(a,key=lambda x: x%2)
[2, 4, 1, 3]
Here sorted
is a function that returns a sorted list. You can also use the sort
method, as John said. Apparently if your original list is not sorted, sorted
will not work, so you then you would have to do:
a = [3,2,1,4]
a.sort()
newList = sorted(a,key=lambda x: x%2)
at which point John's code is probably cleaner. His can also be implemented with the sorted
function though, by doing sorted(a,key=lambda x: (x%2,x))
.
Upvotes: 2