簡體   English   中英

在python中對二維數組進行排序

[英]Sorting a two dimensional array in python

entropies_with_samples = []
for i in range(0,2948):
    entr = entropy(predictProbas[i])
    mixed = [proba_X_train[i],entr]
    entropies_with_samples.append(mixed)

a = np.array(entropies_with_samples)
a.flatten("F")
print(list(chain.from_iterable(entropies_with_samples)))
selection = (sorted(mixed, key=itemgetter(2),reverse= True))
print(selection)

例:

input = [([0.2,0.10]),0.69, ([0.3,0.67]),0.70, ([0.5,0.68]),0.70, ([0.3,0.67]),0.65]

我正在嘗試在第三位置對此類數組進行排序。

output = [([0.3,0.67]),0.70,  ([0.5,0.68]),0.70, ([0.2,0.10]),0.69, ([0.3,0.67]),0.65 ]

第一步可能是創建一個嵌套列表,將每2元素添加到一個新的子列表中:

from itertools import chain
from operator import itemgetter

i = [([0.2,0.10]),0.69, ([0.3,0.67]),0.70, ([0.5,0.68]),0.70, ([0.3,0.67]),0.65]

l = [i[x:x+2] for x in range(0, len(i),2)]
# [[[0.2, 0.1], 0.69], [[0.3, 0.67], 0.7], [[0.5, 0.68], 0.7], [[0.3, 0.67], 0.65]]

然后使用operator.itemgetter將嵌套列表按每個子列表中的第二個元素排序,並使用itertools.chain展平結果:

list(chain(*sorted(l, key = itemgetter(1), reverse=True)))

[[0.3, 0.67], 0.7, [0.5, 0.68], 0.7, [0.2, 0.1], 0.69, [0.3, 0.67], 0.65]

使用zip和使用lambda排序鍵進行排序的另一種方法是:

首先,使用zip將您的“第三位置”與第一個和第二個數字放在一個元組中:

output = list(zip(output[::2], output[1::2]))
#[([0.3, 0.67], 0.7), ([0.5, 0.68], 0.7), ([0.2, 0.1], 0.69), ([0.3, 0.67], 0.65)]

然后使用您的第三個數字(在元組中位於位置2)作為排序鍵進行排序:

output.sort(key = lambda x: x[1])
#[([0.3, 0.67], 0.65), ([0.2, 0.1], 0.69), ([0.3, 0.67], 0.7), ([0.5, 0.68], 0.7)]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM