【发布时间】:2018-09-05 07:53:59
【问题描述】:
我正在尝试按命名元组的最后一个“元素”以递减顺序(从最大到最小)对命名元组列表进行排序。这是我要排序的命名元组列表的 sn-p:
>>> a =[]
>>> a += [p]
>>> a
[Point(x=11, y=22)]
>>> total = []
>>> b = Point(1,33)
>>> b
Point(x=1, y=33)
>>> c = Point(99, 2)
>>> total += [b] + [c] + [p]
>>> total
[Point(x=1, y=33), Point(x=99, y=2), Point(x=11, y=22)]
>>> sorted(total, key = lambda x: x[y], reverse = True)
Traceback (most recent call last):
File "<pyshell#26>", line 1, in <module>
sorted(total, key = lambda x: x[y], reverse = True)
File "<pyshell#26>", line 1, in <lambda>
sorted(total, key = lambda x: x[y], reverse = True)
NameError: name 'y' is not defined
>>> sorted(total, key = lambda x: x['y'], reverse = True)
Traceback (most recent call last):
File "<pyshell#27>", line 1, in <module>
sorted(total, key = lambda x: x['y'], reverse = True)
File "<pyshell#27>", line 1, in <lambda>
sorted(total, key = lambda x: x['y'], reverse = True)
TypeError: tuple indices must be integers or slices, not str
但是,我不断收到上述错误。有没有办法为此类命名元组实例执行此操作?
作为粗略的指南,命名元组的列表是total,我正在尝试将元组从最大的y 排序到最小的y。所以结果应该是这样的:
>>> total
[Point(x=1, y=33), Point(x=11, y=22), Point(x=99, y=2)]
namedtuple 的文档位于:https://docs.python.org/3/library/collections.html#collections.namedtuple。
感谢您的帮助,我们将不胜感激!
【问题讨论】:
标签: python python-3.x sorting tuples namedtuple