I want to sort a list of named tuples without having to remember the index of the fieldname. My solution seems rather awkward and was hoping someone would have a more elegant solution.
from operator import itemgetter from collections import namedtuple Person = namedtuple('Person', 'name age score') seq = [ Person(name='nick', age=23, score=100), Person(name='bob', age=25, score=200), ] # sort list by name print(sorted(seq, key=itemgetter(Person._fields.index('name')))) # sort list by age print(sorted(seq, key=itemgetter(Person._fields.index('age'))))
Thanks, Nick
The easiest way to accomplish this task is to call Python's built-in sorted() function that takes an iterable and returns a new list with sorted elements. The sorted() function generates a new sorted list that is put into the print() function that prints the sorted list to the shell.
Based on the results of the key function, you can sort the given list. Here, len is Python's in-built function to count the length of an element. The list is sorted based on the length of each element, from lowest count to highest. We know that a tuple is sorted using its first parameter by default.
count() and . index() , namedtuple classes also provide three additional methods and two attributes. To prevent name conflicts with custom fields, the names of these attributes and methods start with an underscore. In this section, you'll learn about these methods and attributes and how they work.
from operator import attrgetter from collections import namedtuple Person = namedtuple('Person', 'name age score') seq = [Person(name='nick', age=23, score=100), Person(name='bob', age=25, score=200)]
Sort list by name
sorted(seq, key=attrgetter('name'))
Sort list by age
sorted(seq, key=attrgetter('age'))
sorted(seq, key=lambda x: x.name) sorted(seq, key=lambda x: x.age)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With