Python:排序数组的交替元素

2024-10-02 08:25:51 发布

您现在位置:Python中文网/ 问答频道 /正文

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

在爪哇,我可以这样做:

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中做同样的事情,除了向后。关于如何将执行古怪排序的最后一个for循环转换为python并使其倒退,有什么想法吗?在


Tags: thegt目标newforby排序array
3条回答

正如我在对你上一个问题的评论中所说的,你想要做的最简单的方法就是先写一个函数,把已经排序的列表交换成你想要的顺序,然后你就可以把你的排序函数和新函数连在一起。在

def wacky_sort(seq):
    # code you already have

def alternate_ends(seq):
    new_seq = []
    while seq:
        new_seq.append(seq.pop(0))
        if seq:
            new_seq.append(seq.pop())
    return new_seq

def wacky_sort_with_alternating_ends(seq):
    wacky_sort(seq)
    return alternate_ends(seq)
nums = [1, 2, 3, 4]
newarray = sum(zip(reversed(nums), nums), ())[:len(nums)]

>>> print(newarray)
(4, 1, 3, 2)

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

^{pr2}$

那么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([(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)))

我建议先按正常顺序排序,然后再洗牌:

inlist=[3,5,7,6,9,8,2,1]
inlist.sort()
outlist=[]
while len(inlist)>0:
  if (len(outlist)%2==0):
      outlist.append(inlist.pop())
  else:
      outlist.append(inlist.pop(0))

相关问题 更多 >

    热门问题