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

example: 例:

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]

I'm trying to sort such an array at the third position. 我正在尝试在第三位置对此类数组进行排序。

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 ]

A first step could be to create a nested list, adding every 2 elements to a new sublist: 第一步可能是创建一个嵌套列表,将每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]]

And then sort the nested list by the second element in each sublist with operator.itemgetter , and use itertools.chain to flatten the result: 然后使用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]

Another approach with zip and sorting with a lambda sorting key: 使用zip和使用lambda排序键进行排序的另一种方法是:

First, put your "third position" in a tuple with the first and second number, using 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)]

And then sort, using your third number (in the tuple it's on position 2) as the sorting key: 然后使用您的第三个数字(在元组中位于位置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