简体   繁体   中英

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:

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:

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:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM