在一个声明中对列表理解进行排序

don*_*pj2 20 python list-comprehension

我注意到今天早上写剧本时我没想到的东西.我尝试使用列表理解并在一个语句中对其进行排序,并得到了令人惊讶的结果.以下代码总结了我的一般用例,但针对此问题进行了简化:

Transaction = namedtuple('Transaction', ['code', 'type'])

my_list = [Transaction('code1', 'AAAAA'), Transaction('code2', 'BBBBB'), Transaction('code3', 'AAAAA')]

types = ['AAAAA', 'CCCCC']

result = [trans for trans in my_list if trans.type in types].sort(key = lambda x: x.code)

print result
Run Code Online (Sandbox Code Playgroud)

输出:

None
Run Code Online (Sandbox Code Playgroud)

如果我使用理解创建列表,然后在事实之后对其进行排序,一切都很好.我很好奇为什么会这样?

Sve*_*ach 38

该方法list.sort()正在对列表进行排序,并返回所有变异方法None.使用内置函数sorted()返回新的排序列表.

result = sorted((trans for trans in my_list if trans.type in types),
                key=lambda x: x.code)
Run Code Online (Sandbox Code Playgroud)

而不是lambda x: x.code,你也可以使用稍快operator.attrgetter("code").


mgi*_*son 5

你想要sorted内置函数。该sort方法对列表进行就地排序并返回None

result = sorted([trans for trans in my_list if trans.type in types],key = lambda x: x.code)
Run Code Online (Sandbox Code Playgroud)

这可以通过以下方式做得更好:

import operator
result = sorted( (trans for trans in my_list if trans.type in types ), key=operator.attrgetter("code"))
Run Code Online (Sandbox Code Playgroud)