如何在Python中对以下结构排序

2024-05-16 11:29:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我有下面的Python列表。你知道吗

[[53.60495722746216, 'Percent Cats'],
 [45.298311033121294, 'Percent Dogs'],
 [1.0967317394165388, 'Percent Horses']]

现在我想要百分比最高的动物。在这种情况下,它将是Cats。你知道吗

如何对这个结构进行排序以获取值?你知道吗


Tags: 列表排序情况结构百分比动物percentdogs
2条回答
a = [[53.60495722746216, 'Percent Cats'], [45.298311033121294, 'Percent Dogs'], [1.0967317394165388, 'Percent Horses']]
print sorted(a, key=lambda x:x[0], reverse=True)[0]

如果只需要得到一个值,则不需要对列表进行排序。使用内置的^{}函数和这样的自定义排序函数

In [3]: max(l, key=lambda x: x[0])[1] # compare first elements of inner lists
Out[3]: 'Percent Cats'

甚至

In [4]: max(l)[1] # compare lists directly
Out[4]: 'Percent Cats'

后面的代码也可以工作,因为sequence objects may be compared to other objects with the same sequence type

The comparison uses lexicographical ordering: first the first two items are compared, and if they differ this determines the outcome of the comparison; if they are equal, the next two items are compared, and so on, until either sequence is exhausted. If all items of two sequences compare equal, the sequences are considered equal.

相关问题 更多 >