2

I am having a hard time to find proper syntax of list.sort command to pick up correct highest value from array. I have following list of objects:

[((6, (192, 96, 128)), 1), ((49, (128, 32, 64)), 1), ((2, (128, 96, 0)), 1),
 ((4, (160, 160, 160)), 1), ((41977, (64, 160, 160)), 1), ((1787, (128, 32, 128)), 1),
 ((8, (128, 96, 160)), 1), ((1, (192, 96, 160)), 1), ((14381, (0, 0, 32)), 1),
 ((2, (64, 96, 64)), 1), ((9, (192, 128, 160)), 1), ((410, (64, 32, 64)), 1),
 ((75, (192, 160, 96)), 1), ((6, (96, 0, 32)), 1), ((142163, (0, 160, 128)), 1),
 ((2468, (224, 192, 64)), 1), ((95, (64, 0, 32)), 1), ((224, (0, 128, 160)), 1),
 ((57, (96, 32, 32)), 1), ((40, (160, 96, 64)), 1)]

and I would like to sort it so I pick up the highest value: ((142163, (0, 160, 128)), 1)

Can someone please help me to construct a command that either sorts the list in descending order, or picks up the max() value of 142163 and returns its associated element (0,160,128)?

Thank you very much!

2

2 Answers 2

4

in your case, you don't need to sort (O(log(n)*n) complexity) since you only need one value. The fastest is just to use max (O(n) complexity) as the order of your structures follows the natural order

>>> max(x)
((142163, (0, 160, 128)), 1)

max also accepts a key argument for more complex sorting cases.

Sign up to request clarification or add additional context in comments.

Comments

3
  • you can pass key in sorted function of python. You can also use sort function which is inplace function.
lst = [((6, (192, 96, 128)), 1), ((49, (128, 32, 64)), 1), ((2, (128, 96, 0)), 1), ((4, (160, 160, 160)), 1), ((41977, (64, 160, 160)), 1), ((1787, (128, 32, 128)), 1), ((8, (128, 96, 160)), 1), ((1, (192, 96, 160)), 1), ((14381, (0, 0, 32)), 1), ((2, (64, 96, 64)), 1), ((9, (192, 128, 160)), 1), ((410, (64, 32, 64)), 1), ((75, (192, 160, 96)), 1), ((6, (96, 0, 32)), 1), ((142163, (0, 160, 128)), 1), ((2468, (224, 192, 64)), 1), ((95, (64, 0, 32)), 1), ((224, (0, 128, 160)), 1), ((57, (96, 32, 32)), 1), ((40, (160, 96, 64)), 1)]
lst = sorted(lst, key = lambda x:x[0][0], reverse=True) # sort by first element of first tuple of each object. reverse=True will give you decending order
print(lst[0])
print(lst[0][0][1])
  • output
((142163, (0, 160, 128)), 1)
(0, 160, 128)

1 Comment

@Jean-FrançoisFabre I know but the point is to give OP idea of key parameter of sorted function for future reference. Explicit is better than implicit. (Reference python.org/dev/peps/pep-0020)

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.