[英]How to sort objects in Python
I am having a hard time to find proper syntax of list.sort command to pick up correct highest value from array.我很难找到 list.sort 命令的正确语法来从数组中获取正确的最大值。 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)
我想对其进行排序,因此我选择了最高值: ((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)?有人可以帮我构建一个命令,该命令要么按降序对列表进行排序,要么获取 142163 的 max() 值并返回其关联元素 (0,160,128)?
Thank you very much!非常感谢!
in your case, you don't need to sort ( O(log(n)*n)
complexity) since you only need one value.在您的情况下,您不需要排序( O(log(n)*n)
复杂度),因为您只需要一个值。 The fastest is just to use max
( O(n)
complexity) as the order of your structures follows the natural order最快的就是使用max
( O(n)
复杂度),因为结构的顺序遵循自然顺序
>>> max(x)
((142163, (0, 160, 128)), 1)
max
also accepts a key
argument for more complex sorting cases. max
还接受更复杂的排序情况的key
参数。
sorted
function of python.您可以在 python 的sorted
function 中传递密钥。 You can also use sort
function which is inplace function.您还可以使用sort
function 代替 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])
((142163, (0, 160, 128)), 1)
(0, 160, 128)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.