我对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式的方法来完成这一点?显然,前面的列表理解会给出一个列表列表。
你是说这样的事吗?
或更短的代码(但不是最优的):
或同样:
感谢@eyquem的提示(如果使用Python 2.x):
更简单、更清晰的列表理解:
Python的就地add运算符(
+=
,在operator
模块中可用作iadd
)相当于列表的.extend
。把它和reduce
配对得到你想要的。相关问题 更多 >
编程相关推荐