Python:元素列表
请,如果我有一个元组列表,例如:
list = [('James',27,2000),('Aaron',24,1290),('Max',23,2300),('Ben', 27,1900)]
我如何按顺序获得所有名称?
如何获得以姓名上升顺序显示元组的列表?
谢谢
Please, if I have a list of tuples, say:
list = [('James', 27, 2000), ('Aaron', 24, 1290), ('Max', 23, 2300), ('Ben', 27, 1900)]
How do I get all the names in ascending order?
How do I get a list that shows the tuples in ascending order of names?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
如果您对元组进行排序,则默认情况下,将元组中的第一项作为钥匙。因此:
输出:
或,如果您想要元素,
则会产生:...
If you sort a list of tuples, by default the first item in the tuple is taken as the key. Therefore:
Output:
Or, if you want the tuples then:
...which produces:
假设您是字母顺序的?
您可以使用
排序
:输出:
Assuming by ascending you mean alphabetical?
You can do it with
sorted
:Output:
印刷
Prints
输出:
输出:
Output:
Output:
请注意,
list
是Python中的对象,因此,当您使用名称list
创建一个变量时,您覆盖该参考在您的程序中。Be advised that
list
is an object in Python, so when you create a variable with the namelist
, you overwrite that reference and you cannot uselist(something)
after in your program.您可以在
中使用
键
sort> sort
或排序
函数。这是一个示例:结果将是:
您可以使用列表理解来从排序列表中提取名称:
You can use
key
parameter insort
orsorted
function. Here's an example:And the result will be:
You can use list comprehension to extract names from sorted list: