对列表中的奇数进行排序

phy*_*ist 3 python

如何在整数列表中对奇数进行排序,但将偶数保留在原始位置?

例:

sortArray([5, 3, 2, 8, 1, 4]) == [1, 3, 2, 8, 5, 4]
Run Code Online (Sandbox Code Playgroud)

我的代码:

def sort_array(source_array):     
    odd_numbers = [n for n in source_array if n%2!=0]
    odd_numbers = sorted(odd_numbers)
Run Code Online (Sandbox Code Playgroud)

如何切换奇数的索引source_arrayodd_numbers

Jon*_*nts 10

看起来你几乎就在那里 - 你可以使你的排序奇数成为可迭代的,并使用原始偶数或下一个排序的奇数重建你的源列表,例如:

>>> data = [5, 3, 2, 8, 1, 4]
>>> odds = iter(sorted(el for el in data if el % 2))
>>> [next(odds) if el % 2 else el for el in data]
[1, 3, 2, 8, 5, 4]
Run Code Online (Sandbox Code Playgroud)


Xuy*_*iao 5

更多行数但也更具可读性

a = [5, 3, 2, 8, 1, 4]
b = sorted([item for item in a if item%2 != 0])
odd_int = 0
for i in range(len(a)):
    if a[i] %2 != 0:
        a[i] = b[odd_int]
        odd_int += 1
Run Code Online (Sandbox Code Playgroud)