繁体   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