I want to sort a list in Python3, first odd numbers, then even numbers.
Let the list is li = [4, 1, 5, 8, 2, 9, 3, 10, 7, 6]
Output should be: 1 3 5 7 9 2 4 6 8 10
How to solve this using function or lambda or any other way?
#Edited
using lambda only.
CodePudding user response:
You're effectively sorting on two keys: the primary key is whether the int is even or odd, and you want odd to compare "smaller". The secondary key is then the integer itself. That can all be expressed by sorting on tuples of (primary key, secondary key), which can be expressed by building those tuples straightforwardly via a function passed to sorting's optional key= argument:
>>> li = [4, 1, 5, 8, 2, 9, 3, 10, 7, 6]
>>> sorted(li, key=lambda i: (1 - (i & 1), i))
[1, 3, 5, 7, 9, 2, 4, 6, 8, 10]
CodePudding user response:
We take the list, filter only the odd values, sort, and splat the values and do the exact same but for evens.
li = [4, 1, 5, 8, 2, 9, 3, 10, 7, 6]
final_li = [*sorted(filter(lambda x: x % 2, li)), *sorted(filter(lambda x: x % 2 == 0, li))]
CodePudding user response:
This should work:
array = [4, 1, 5, 8, 2, 9, 3, 10, 7, 6]
even = []
odd = []
for value in sorted(array):
if value % 2 == 0:
even.append(value)
else:
odd.append(value)
combined = even odd
print(*combined)
CodePudding user response:
here is one way (if there is no duplicate number in the list):
li = [4, 1, 5, 8, 2, 9, 3, 10, 7, 6]
sorted_li = sorted(li)
print([*sorted_li[::2] , *sorted_li[1::2]])
output:
[1, 3, 5, 7, 9, 2, 4, 6, 8, 10]
I'm sorting the whole list once , then make a new list by slicing that sorted list , which first I pick odd numbers , which since they are sorted , are every other number from index 0 , and then even numbers , the same concept , this time even numbers start from index 1 , then I unpack them into one list in that order
