在我的小项目中,我按降序排列了一个列表,但是,我的目标是在此自定义模式中对其进行排序.(最大 - >最小 - >次最大 - >次最小 - >)等.
在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];
}
}
Run Code Online (Sandbox Code Playgroud)
我的目标是在python中做同样的事情,除了向后.关于如何将最后一个转换为循环的任何想法,将wackysort转换为python并使其向后移动?
我建议先正常排序,然后再进行洗牌:
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))
Run Code Online (Sandbox Code Playgroud)
nums = [1, 2, 3, 4]
newarray = sum(zip(reversed(nums), nums), ())[:len(nums)]
>>> print(newarray)
(4, 1, 3, 2)
Run Code Online (Sandbox Code Playgroud)
它是做什么的,一步一步.首先,反转():
>>> list(reversed(nums))
[4, 3, 2, 1]
Run Code Online (Sandbox Code Playgroud)
然后zip():
>>> list(zip([4, 3, 2, 1], [1, 2, 3, 4]))
[(4, 1), (3, 2), (2, 3), (1, 4)]
Run Code Online (Sandbox Code Playgroud)
你可以看到我们几乎有我们想要的列表,我们有一个问题:这些是元组.我们想要压扁它们.
>>> (4, 1) + (3, 2) + (2, 3) + (1, 4)
(4, 1, 3, 2, 2, 3, 1, 4)
Run Code Online (Sandbox Code Playgroud)
哦.真好.但如何在列表中做到这一点?简单:使用sum(),这正是这一点 - 将许多东西放在一起.只有我们需要给它一些东西 - 一个空的元组():
>>> sum([(4, 1), (3, 2), (2, 3), (1, 4)], ())
(4, 1, 3, 2, 2, 3, 1, 4)
Run Code Online (Sandbox Code Playgroud)
但是我们不想要下半场,所以让我们删除它.我们知道他的名单正好是两倍太长,是吗?
>>> (4, 1, 3, 2, 2, 3, 1, 4)[:len(nums)]
(4, 1, 3, 2)
Run Code Online (Sandbox Code Playgroud)
而已.
另外一个选项:
from itertools import chain, islice
a = list(islice(chain.from_iterable(zip(nums, reversed(nums))), len(nums)))
Run Code Online (Sandbox Code Playgroud)