0

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

1
  • Check out the sorted builtin function. Commented Sep 15, 2017 at 19:42

1 Answer 1

2

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]]
Sign up to request clarification or add additional context in comments.

3 Comments

You don't need to specify the key for your outer call to sorted.
@ZachGates Oh yes, I do. I don't want to assume the tuples will never tie, in which case a keyless sort will break ties using the percentage, which is not what they want.
Fair enough. After reading the question again, OP did say to ignore the percentage. Good answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.