(Python) 按命名元组中最后一个元素的降序排序

(Python) Sorting in decreasing sequence of the last element in a namedtuple

我正在尝试按最后一个 'element' 以递减顺序(从最大到最小)对命名元组列表进行排序。这是我要排序的命名元组列表的片段:

>>> 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

但是,我不断收到上述错误。有没有办法对此类 namedtuple 实例执行此操作?

作为粗略指南,namedtuples 列表是 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

谢谢,我们将不胜感激!

您正在寻找以下内容:

sorted(total, key = lambda x: x.y, reverse = True)