在我的小项目中,我已经按降序排列了一个列表,但是,我的目标是按照这个自定义模式对它进行排序。(最大->;最小->;次大->;次小->;)等
在爪哇,我可以这样做:
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并使其倒退,有什么想法吗?在
正如我在对你上一个问题的评论中所说的,你想要做的最简单的方法就是先写一个函数,把已经排序的列表交换成你想要的顺序,然后你就可以把你的排序函数和新函数连在一起。在
它的作用,一步一步。首先,reversed():
^{pr2}$那么zip():
你可以看到我们几乎得到了我们想要的列表,我们有一个问题:这些是元组。我们要把它们弄平。在
哦。太好了。但如何在列表中做到这一点呢?简单:使用^{} ,这正是这样做的-将许多事情添加到一起。我们只需要给它一个空的元组
()
:但是我们不想要下半场,所以我们把它去掉。我们知道他的名单太长了一倍,是吗?在
就这样。在
另一个选择:
我建议先按正常顺序排序,然后再洗牌:
相关问题 更多 >
编程相关推荐