我想对命名元组列表进行排序,而不必记住fieldname的索引。我的解决方案似乎相当尴尬,并希望有人能有更优雅的解决方案。
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'))))
谢谢, 尼克
答案 0 :(得分:66)
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)]
按名称排序列表
sorted(seq, key=attrgetter('name'))
按年龄排序列表
sorted(seq, key=attrgetter('age'))
答案 1 :(得分:47)
sorted(seq, key=lambda x: x.name)
sorted(seq, key=lambda x: x.age)
答案 2 :(得分:6)
我测试了这里给出的两种替代方案的速度,因为@zenpoy关注性能。
测试脚本:
import random
from collections import namedtuple
from timeit import timeit
from operator import attrgetter
runs = 10000
size = 10000
random.seed = 42
Person = namedtuple('Person', 'name,age')
seq = [Person(str(random.randint(0, 10 ** 10)), random.randint(0, 100)) for _ in range(size)]
def attrgetter_test_name():
return sorted(seq.copy(), key=attrgetter('name'))
def attrgetter_test_age():
return sorted(seq.copy(), key=attrgetter('age'))
def lambda_test_name():
return sorted(seq.copy(), key=lambda x: x.name)
def lambda_test_age():
return sorted(seq.copy(), key=lambda x: x.age)
print('attrgetter_test_name', timeit(stmt=attrgetter_test_name, number=runs))
print('attrgetter_test_age', timeit(stmt=attrgetter_test_age, number=runs))
print('lambda_test_name', timeit(stmt=lambda_test_name, number=runs))
print('lambda_test_age', timeit(stmt=lambda_test_age, number=runs))
结果:
attrgetter_test_name 44.26793992166096
attrgetter_test_age 31.98247099677627
lambda_test_name 47.97959511074551
lambda_test_age 35.69356267603864
使用lambda确实比较慢。慢了10%。
修改强>:
进一步测试显示使用多个属性进行排序时的结果。添加了以下两个具有相同设置的测试用例:
def attrgetter_test_both():
return sorted(seq.copy(), key=attrgetter('age', 'name'))
def lambda_test_both():
return sorted(seq.copy(), key=lambda x: (x.age, x.name))
print('attrgetter_test_both', timeit(stmt=attrgetter_test_both, number=runs))
print('lambda_test_both', timeit(stmt=lambda_test_both, number=runs))
结果:
attrgetter_test_both 92.80101586919373
lambda_test_both 96.85089983147456
Lambda仍然表现不佳,但不那么糟糕。现在慢了约5%。
测试在Python 3.6.0上完成。
答案 3 :(得分:0)
因为没有人提到使用itemgetter(),这里你是如何使用itemgetter()。
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(0)))
# sort list by age
print(sorted(seq, key=itemgetter(1)))
答案 4 :(得分:0)
对于某些人来说这可能有点“神奇”,但是我偏爱:
# sort list by name
print(sorted(seq, key=Person.name.fget))