Python Forum
Thread Rating:
  • 2 Vote(s) - 3.5 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Sort only the odd numbers
#6
#!/usr/bin/env/python3

original_list = [1,5,3,2,7,7,3,2,7]

def sort_odds(lst):
    sorted_odds = sorted([n for n in lst if n%2])
    new_list = []
    for n in lst:
        if n%2:
            new_list.append(sorted_odds.pop(0))
        else:
            new_list.append(n)
    return list(new_list)
print(sort_odds(original_list))
if efficiency is concern, you may use collections.deque to optimize the popleft operation

#!/usr/bin/env/python3

from collections import deque

original_list = [1,5,3,2,7,7,3,2,7]

def sort_odds(lst):
    sorted_odds = deque(sorted([n for n in lst if n%2])) #using deque to optimize pop
    new_list = []
    for n in lst:
        if n%2:
            new_list.append(sorted_odds.popleft())
        else:
            new_list.append(n)
    return list(new_list)
print(sort_odds(original_list))
Reply


Messages In This Thread
Sort only the odd numbers - by tomhuang - Jul-20-2017, 05:10 PM
RE: Sort only the odd numbers - by Bass - Jul-20-2017, 05:15 PM
RE: Sort only the odd numbers - by nilamo - Jul-20-2017, 06:00 PM
RE: Sort only the odd numbers - by ichabod801 - Jul-20-2017, 06:02 PM
RE: Sort only the odd numbers - by ichabod801 - Jul-20-2017, 06:07 PM
RE: Sort only the odd numbers - by buran - Jul-20-2017, 08:30 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
Photo a.sort() == b.sort() all the time 3lnyn0 1 1,403 Apr-19-2022, 06:50 PM
Last Post: Gribouillis
  Print Numbers starting at 1 vertically with separator for output numbers Pleiades 3 3,856 May-09-2019, 12:19 PM
Last Post: Pleiades
  Need Help: Sort of Binary numbers based on 1's present abinashj 5 5,189 Jul-25-2017, 12:23 PM
Last Post: buran

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020