亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在數組索引中排序到索引

如何在數組索引中排序到索引

喵喔喔 2022-06-28 16:16:25
大家好,我如何將數組索引排序為索引。所以我在這里有代碼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]
查看完整描述

3 回答

?
牧羊人nacy

TA貢獻1862條經驗 獲得超7個贊

我可能是錯的,但聽起來你想返回一個排序如下的列表:


[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]


查看完整回答
反對 回復 2022-06-28
?
小怪獸愛吃肉

TA貢獻1852條經驗 獲得超1個贊

對于那些想要一個并且不能/不想使用熊貓的人來說,這是一個幾乎一個班輪(基于@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]


查看完整回答
反對 回復 2022-06-28
?
慕的地8271018

TA貢獻1796條經驗 獲得超4個贊

有時我們想就地排序,即不創建新列表。這是我想出的


l=[1,2,3,4,5,6,7]

for i in range(1, len(l), 2):

    l.insert(i, l.pop())


查看完整回答
反對 回復 2022-06-28
  • 3 回答
  • 0 關注
  • 156 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號