You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python列表仅排序奇数元素问题求解及代码疑问

Solution to Sort Odd Elements While Keeping Evens in Place

Nice start with separating odds and evens—you’ve got the core idea right! The main missing pieces are how to properly merge the sorted odds back into their original positions (instead of just concatenating lists) and handling the sorting correctly (since list.sort() modifies the list in-place and returns None).

Here’s the polished, working solution:

def sort_array(source_array):
    # Extract all odd numbers and sort them in ascending order
    sorted_odds = sorted(num for num in source_array if num % 2 != 0)
    # Create an iterator to fetch sorted odds one by one
    odd_iterator = iter(sorted_odds)
    # Reconstruct the array: replace each odd with the next sorted odd, keep evens as-is
    return [next(odd_iterator) if num % 2 != 0 else num for num in source_array]

Breakdown of the Fixes:

  • Using sorted() instead of list.sort(): Unlike sort(), which modifies the list in-place and returns None, sorted() returns a new sorted list—perfect for our use case since we need to keep the original order of positions intact.
  • Iterator for sorted odds: By turning sorted_odds into an iterator, we can efficiently grab the next sorted odd each time we encounter an odd in the original array. This ensures we place the sorted odds exactly where the original odds were.
  • List comprehension for merging: The comprehension loops through the original array, checking each element. If it’s odd, we pull the next sorted odd from our iterator; if it’s even, we leave it in its original position.

Example Usage:

If you pass [5, 3, 2, 8, 1, 4] to the function, it will return [1, 3, 2, 8, 5, 4]—the odds are sorted, and evens stay in their original spots.

What Was Off in Your Original Code?

Your initial approach separated odds and evens correctly, but merging them by just returning odd_arr.sort(...) wouldn’t work because:

  1. odd_arr.sort() returns None, not the sorted list.
  2. Concatenating odd_arr and even_arr would put all odds first, which destroys the original positions of even elements.

This solution fixes both issues while keeping your original logical foundation intact!

内容的提问来源于stack exchange,提问作者SaiBorg

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 08:32:53