简体   繁体   English

如何根据列表值对元组进行排序?

[英]How to sort tuple according to list value?

I have a with this structure: 我有一个这样的结构:

players={ 'Player one': [3, 0], 'Player two': [13, 1], 'Player three': [29, 0], 'Player four': [19, 5] }

The first number of the list is the number of games and the next is the number of goals. 列表的第一个数字是游戏数,第二个是目标数。

To sort the array by the number of games I just use: 要按照我使用的游戏数量对数组进行排序:

print sorted(players.items(), key=lambda kv:(kv[1], kv[0]),reverse=True)

This works great but I found no way to sort by the number of goals (the second number of the list). 效果很好,但我找不到按目标数量(列表的第二个数量)排序的方法。 What is the easiest way to do this? 最简单的方法是什么?

You could sort exclusively by the second number of the list with this: 您可以按以下方式仅按列表的第二个数字排序:

sorted(players.items(), key=lambda kv: kv[1][1], reverse=True)

Where lambda kv: kv[1][1] basically extracts the second [1] value of each list kv[1] 其中lambda kv: kv[1][1]基本上提取每个列表kv[1]的第二个[1]

You can simply specify searching through the second index: 您只需在第二个索引中指定搜索即可:

players={ 'Player one': [3, 0], 'Player two': [13, 1], 'Player three': [29, 0], 'Player four': [19, 5] }

sorted(players.items(), key=lambda kv:(kv[1][1], kv[0]),reverse=True))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM