0

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!

Stoner
  • 846
  • 1
  • 10
  • 30

1 Answers1

1

You're looking for the following:

sorted(total, key = lambda x: x.y, reverse = True)
Mikhail Burshteyn
  • 4,762
  • 14
  • 27
  • Thank you! Silly mistake on my part – Stoner Sep 05 '18 at 07:58
  • Yes! I am waiting for the the 15 minute mark as stackoverflow does not allow me to accept the answer within 15 minutes of posting the question haha. You answered too quickly ;) – Stoner Sep 05 '18 at 08:07