0

I'm fairly new to using python. I have a list of namedtuples which I would like to sort numerically by one of the fields. I currently have code that looks something like this:

from collections import namedtuple

testTuple = namedtuple("test", "name, number")
from operator import itemgetter

testList = []
seq = [testTuple(name = 'abc', number = '123'),
testTuple(name = 'xyz', number = '32'),
testTuple(name = 'def', number = '322')]
print(sorted(seq, key= itemgetter(1)))

But of course since itemgetter sorts alphabetically the tuple associated with 123 is printed before that associated with 32. I'm unsure if I can somehow combine key=itemgetter(x) with key=int to solve my issue.

Shani de Leeuw
  • 171
  • 1
  • 11

1 Answers1

4

I think that writing a small lambda function is best you'll be able to do:

from collections import namedtuple

testTuple = namedtuple("test", ("name", "number"))

seq = [testTuple(name = 'abc', number = '123'),
       testTuple(name = 'xyz', number = '32'),
       testTuple(name = 'def', number = '322')]

print(sorted(seq, key=lambda x: int(x[1])))

# Output:
# [test(name='xyz', number='32'), test(name='abc', number='123'), test(name='def', number='322')]
user94559
  • 59,196
  • 6
  • 103
  • 103