猿问

如何在数组索引中排序到索引

大家好,我如何将数组索引排序为索引。所以我在这里有代码

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]

喵喔喔
浏览 161回答 3
3回答

牧羊人nacy

我可能是错的,但听起来你想返回一个排序如下的列表:[first_item, last_item, second_item, second_to_last_item, third_item, third_to_last_item,...]我不知道有一种方法可以做到这一点,但这里有一种方法可以做到:import numpy as npa = [0, 1, 2, 3, 7] # length of list is an odd number# create indexes that are all positiveindex_values = np.repeat(np.arange(0, len(a)//2 + 1), 2) # [0,0,1,1,.....]# make every other one negativeindex_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 numberindex_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_longestdef 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]

慕的地8271018

有时我们想就地排序,即不创建新列表。这是我想出的l=[1,2,3,4,5,6,7]for i in range(1, len(l), 2):    l.insert(i, l.pop())
随时随地看视频慕课网APP

相关分类

Python
我要回答