【问题标题】:(Python) Sorting in decreasing sequence of the last element in a namedtuple(Python)按命名元组中最后一个元素的递减顺序排序
【发布时间】: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


    【解决方案1】:

    您正在寻找以下内容:

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

    【讨论】:

    • 谢谢!我犯了一个愚蠢的错误
    • 是的!我正在等待 15 分钟标记,因为 stackoverflow 不允许我在发布问题后的 15 分钟内接受答案哈哈。你回答得太快了;)
    猜你喜欢
    • 2019-09-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-27
    • 1970-01-01
    • 1970-01-01
    • 2022-06-27
    • 2021-03-12
    • 1970-01-01
    相关资源
    最近更新 更多