在python中排序二维数组

2024-05-23 19:32:02 发布

您现在位置: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 ]

Tags: inforwithrangetrainentropysamplesprint
2条回答

另一种方法是使用lambda排序键进行zip和排序:

首先,使用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)]

第一步可以是创建嵌套列表,将每个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按每个子列表中的第二个元素对嵌套列表进行排序,并使用^{}将结果展平:

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]

相关问题 更多 >