在一个语句中对列表理解进行排序 [英] Sorting A List Comprehension In One Statement

查看:65
本文介绍了在一个语句中对列表理解进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天早上写脚本时,我注意到了意料之外的事情.我尝试使用列表理解并将其全部排序为一条语句,并获得了令人惊讶的结果.以下代码总结了我的一般用例,但针对该问题进行了简化:

I noticed something I didn't expect when writing a script this morning. I tried to use a list comprehension and sort it all in one statement and got a surprising result. The following code summarizes my general use case, but is simplified for this question:

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

输出:

None

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

If I create the list using the comprehension, then sort it after the fact, everything is fine. I'm curious why this happens?

推荐答案

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

The method list.sort() is sorting the list in place, and as all mutating methods it returns None. Use the built-in function sorted() to return a new sorted list.

result = sorted((trans for trans in my_list if trans.type in types),
                key=lambda x: x.code)

您也可以使用速度稍快的operator.attrgetter("code")代替lambda x: x.code.

Instead of lambda x: x.code, you could also use the slightly faster operator.attrgetter("code").

这篇关于在一个语句中对列表理解进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆