Skip to main content
 首页 » 编程设计

Python:排序数组的交替元素

2025年05月04日13cmt

在我这里的小项目中,我按降序对列表进行了排序,但是,我的目标是按照此自定义模式对其进行排序。 (最大 -> 最小 -> 次大 -> 次小 ->)等。

在 java 中我可以这样做:

public static void wackySort(int[] nums) { 
    //first, this simply sorts the array by ascending order. 
    int sign = 0; 
    int temp = 0; 
    int temp2 = 0; 
    for (int i = 0; i < nums.length; i++) { 
        for (int j = 0; j < nums.length -1; j++){ 
            if (nums[j] > nums[j+1]) { 
               temp = nums[j]; 
               nums[j] = nums[j+1]; 
               nums[j+1] = temp; 
            } 
        } 
    } 
 
    //prepare for new array to actually do the wacky sort. 
    System.out.println(); 
    int firstPointer = 0; 
    int secondPointer = nums.length -1; 
    int[] newarray = new int[nums.length]; 
    int size = nums.length; 
 
    //increment by two taking second slot replacing the last (n-1) term 
    for (int i = 0; i < nums.length -1; i+=2) { 
        newarray[i] = nums[firstPointer++]; 
        newarray[i+1] = nums[secondPointer--]; 
    } 
 
    //store those values back in the nums array     
    for (int i = 0; i < nums.length; i++) { 
        nums[i] = newarray[i]; 
    } 
} 

我的目标是在 python 中做同样的事情,除了向后。关于如何将执行 wackysort 的最后一个 for 循环转换为 python 并使其倒退,有什么想法吗?

请您参考如下方法:

nums = [1, 2, 3, 4] 
newarray = sum(zip(reversed(nums), nums), ())[:len(nums)] 
 
>>> print(newarray) 
(4, 1, 3, 2) 

它的作用,一步一步。首先,reversed() :

>>> list(reversed(nums)) 
[4, 3, 2, 1] 

然后 zip() :

>>> list(zip([4, 3, 2, 1], [1, 2, 3, 4])) 
[(4, 1), (3, 2), (2, 3), (1, 4)] 

你可以看到我们几乎有了我们想要的列表,我们有一个问题:这些是元组。我们想把它们弄平。

>>> (4, 1) + (3, 2) + (2, 3) + (1, 4) 
(4, 1, 3, 2, 2, 3, 1, 4) 

哦。那很好。但是如何在列表中做到这一点?简单:使用 sum() ,正是这样做的——把很多东西加在一起。只需要给它一些东西作为开始 - 一个空元组 ():

>>> sum([(4, 1), (3, 2), (2, 3), (1, 4)], ()) 
(4, 1, 3, 2, 2, 3, 1, 4) 

但是我们不需要下半部分,所以让我们删除它。我们知道他的列表正好长了两倍,是吗?

>>> (4, 1, 3, 2, 2, 3, 1, 4)[:len(nums)] 
(4, 1, 3, 2) 

就是这样。


另一种选择:

from itertools import chain, islice 
a = list(islice(chain.from_iterable(zip(nums, reversed(nums))), len(nums)))