Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何将数组中的索引排序到索引_Python_Sorting - Fatal编程技术网

Python 如何将数组中的索引排序到索引

Python 如何将数组中的索引排序到索引,python,sorting,Python,Sorting,大家好,我如何对数组索引进行排序。 我这里有代码 a = [0, 1, 2, 3, 4, 4, 3, 2, 1, 0, 4, 3, 2, 1, 0, 0, 1, 2, 3, 4] 我怎样才能分类 [0, 4, 1, 3, 2, 2, 3, 1, 4, 0, 4, 0, 3, 1, 2, 2, 1, 3, 0, 4] 我可能错了,但听起来您想返回一个如下排序的列表: [first_item, last_item, second_item, second_to_last_item, third_

大家好,我如何对数组索引进行排序。 我这里有代码

a = [0, 1, 2, 3, 4, 4, 3, 2, 1, 0, 4, 3, 2, 1, 0, 0, 1, 2, 3, 4]
我怎样才能分类

[0, 4, 1, 3, 2, 2, 3, 1, 4, 0, 4, 0, 3, 1, 2, 2, 1, 3, 0, 4]

我可能错了,但听起来您想返回一个如下排序的列表:

[first_item, last_item, second_item, second_to_last_item, third_item, third_to_last_item,...]
我不知道有哪种方法可以做到这一点,但这里有一种方法可以做到:

import numpy as np

a = [0, 1, 2, 3, 7] # length of list is an odd number

# create indexes that are all positive
index_values = np.repeat(np.arange(0, len(a)//2 + 1), 2) # [0,0,1,1,.....]

# make every other one negative
index_values[::2] *= -1 #[-0, 0, -1, 1, ....]

# return a[i]
[a[i] for i in index_values[1:(len(a)+1)]]

### Output: [0, 7, 1, 3, 2]
它也适用于长度均匀的列表:

a = [0, 1, 2, 3, 7, 5] # list length is an even number
index_values = np.repeat(np.arange(0, len(a)//2 + 1), 2) # [0,0,1,1,.....]
index_values[::2] *= -1 #[-0, 0, -1, 1, ....]
[a[i] for i in index_values[1:(len(a)+1)]]

### Output: [0, 5, 1, 7, 2, 3]

这里有一个几乎一行(基于@Callin的排序方法)用于那些想要一行并且不能/不想使用熊猫的人:

from itertools import zip_longest

def custom_sort(a):
    half = len(a)//2
    return [n for fl in zip_longest(a[:half], a[:half-1:-1]) for n in fl if n is not None])
示例:

custom_sort([0, 1, 2, 3, 7])
#[0, 7, 1, 3, 2]
custom_sort([0, 1, 2, 3, 7, 5])
#[0, 5, 1, 7, 2, 3]
这可以在一行中完成,尽管你需要重复数学来找到中间点

[n for x in zip_longest(a[:len(a)//2], a[:(len(a)//2)-1:-1]) for n in x if n is not None]

有时我们希望在不创建新列表的情况下进行适当的排序。这是我想到的

l=[1,2,3,4,5,6,7]
for i in range(1, len(l), 2):
    l.insert(i, l.pop())

请详细解释你的输出。好的。[0]中的示例,[1]输出是[0]=0 a[1]=1,但移动到[2]欢迎使用SO。请花点时间阅读和阅读该页面上的其他链接。这不是一个讨论论坛或教程服务。你应该花一些时间来练习这些例子。它将向您介绍Python为解决您的问题所提供的工具。