Jakeeln
Jakeeln

Reputation: 353

Python Sort values by first list in 2D array containing list and value

I am keeping track of a list, and each set has a percent support (percentage value indicating frequency). Each support is tied to one set.

x:

[('C', 'A'), 66.667]
[('T', 'A'), 50.0]
[('C', 'D'), 66.667]
[('C', 'T'), 66.667]
[('C', 'W'), 83.333]
[('A', 'W'), 66.667]
[('W', 'T'), 50.0]
[('W', 'D'), 50.0]

I would like the array sorted, ignoring the support so that it looks like this:

[('A', 'C'), 66.667]
[('A', 'T'), 50.0]
[('A', 'W'), 66.667]
[('C', 'D'), 66.667]
[('C', 'T'), 66.667]
[('C', 'W'), 83.333]
[('D', 'W'), 50.0]
[('T', 'W'), 50.0]

sort the sets in x[0] then the entire first column

Upvotes: 0

Views: 87

Answers (1)

Moses Koledoye
Moses Koledoye

Reputation: 78546

Sort the tuples, then sort the list:

lst = sorted([[tuple(sorted(x)), y] for x, y in lst], key=lambda x: x[0])
print(lst)

[[('A', 'C'), 66.667], 
 [('A', 'T'), 50.0], 
 [('A', 'W'), 66.667], 
 [('C', 'D'), 66.667], 
 [('C', 'T'), 66.667], 
 [('C', 'W'), 83.333], 
 [('D', 'W'), 50.0], 
 [('T', 'W'), 50.0]]

Upvotes: 2

Related Questions