2011-05-10 148 views
8

我不是在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列表返回一個列表。什麼是最完美的Pythonic方法?顯然,以前的列表理解會列出一個列表。

回答

4

更簡單,更清潔與列表理解:

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

很大的改進!當我回答問題時,我不會使用嵌套列表理解。 – 2017-06-08 13:52:49

4

你的意思是這樣的嗎?

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), []) 
+1

''收益總和(圖(DoSomething的,originalList))[])''有** IMAP更好* *如果Python 2.右鍵如果Python 3 – eyquem 2011-05-10 08:28:43

2

Python的就地添加運算符(+=iaddoperator模塊)相當於.extend的列表。將它與reduce配對即可得到你想要的。

import operator 

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

我不認爲這種情況下有特殊的語法。但是你可以做的for循環更短:

accumulationList += doSomething(x) 

如果你堅持,你可以使用函數式編程壓扁名單:

result = reduce(lambda a,b: a+b, [[i,i*2] for i in range(3)]) 

但我不會把這個Python的,我認爲這是困難閱讀比for循環。

2

我認爲涉及add或iadd的答案在二次時間運行,這可能不是很好。我想嘗試:

from itertools import chain 
accumulation_list = list(chain.from_iterable(doSomething(x) for x in originalList))