按字段按字段排序命名元组列表

时间:2016-07-19 04:25:40

标签: python sorting namedtuple

我是使用python的新手。我有一个namedtuples列表,我想用其中一个字段进行数字排序。我目前的代码看起来像这样:

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)))

但是当然,因为itemgetter按字母顺序排序,所以在与32相关联之前打印与123相关联的元组。我不确定我是否能以某种方式将key = itemgetter(x)与key = int组合以解决我的问题。

1 个答案:

答案 0 :(得分:3)

我认为写一个小lambda函数是你能做的最好的事情:

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')]