Python列表仅排序奇数元素问题求解及代码疑问
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 oflist.sort(): Unlikesort(), which modifies the list in-place and returnsNone,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_oddsinto 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:
odd_arr.sort()returnsNone, not the sorted list.- Concatenating
odd_arrandeven_arrwould 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

