I am trying to sort a list of named tuples by their last 'element', in decreasing sequence (from largest to smallest). Here's a snippet of the list of namedtuples that I am trying to sort:
>>> 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
However, I keep getting the errors above.. Is there a way to do this for such instances of namedtuple?
As a rough guide, the list of namedtuples is total
, and I am trying to sort the tuples from largest y
to smallest y
. So the result should look something like:
>>> total
[Point(x=1, y=33), Point(x=11, y=22), Point(x=99, y=2)]
The documentation for namedtuple can be found at: https://docs.python.org/3/library/collections.html#collections.namedtuple.
Thanks and some help will be deeply appreciated!