如何在python中使用列表理解来扩展列表?

2024-05-15 03:12:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我对Python没有经验,我经常编写如下(简化)代码:

accumulationList = []
for x in originalList:
    y = doSomething(x)
    accumulationList.append(y)
return accumulationList

然后在测试通过后,我重构到

return [doSomething(x) for x in originalList]

但假设结果有点不同,我的循环看起来是这样的:

accumulationList = []
for x in originalList:
    y = doSomething(x)
    accumulationList.extend(y)
return accumulationList

其中,doSomething列表返回一个列表。什么是最Python式的方法来完成这一点?显然,前面的列表理解会给出一个列表列表。


Tags: 方法代码in列表forreturn经验重构
3条回答

你是说这样的事吗?

accumulationList = []
for x in originalList:
    accumulationList.extend(doSomething(x))
return accumulationList

或更短的代码(但不是最优的):

return sum((doSomething(x) for x in originalList), [])

或同样:

return sum(map(doSomething, originalList), [])

感谢@eyquem的提示(如果使用Python 2.x):

import itertools as it

return sum(it.imap(doSomething, originalList), [])

更简单、更清晰的列表理解:

[y for x in originalList for y in doSomething(x)]

Python的就地add运算符(+=,在operator模块中可用作iadd)相当于列表的.extend。把它和reduce配对得到你想要的。

import operator

reduce(operator.iadd, (doSomething(x) for x in originalList)
, accumulation_list)

相关问题 更多 >

    热门问题