2013-03-01 25 views
2

使用zip(*[iter(s)]*n)成語將列表等分爲一個整數。有沒有一種很好的方法來消除它?郵政編碼相反(* [iter(s)] * n)

舉例來說,如果我有以下代碼:

>>> s = [3,4,1,2] 
>>> zip(*[iter(s)]*2) 
[(3, 4), (1, 2)] 

有一些功能func([(3,4),(1,2)]將產生[3,4,1,2]作爲輸出?

編輯:

時間和更多的解決方案可以通過以下多米尼克Kexel鏈接到的問題被發現。

+0

你說得對。這是同樣的問題。 – 2013-03-01 10:40:11

回答

3

itertools.chain.from_iterable

>>> import itertools 
>>> s = [(3, 4), (1, 2)] 
>>> list(itertools.chain.from_iterable(s)) 
[3, 4, 1, 2] 

但是你也可以使用嵌套列表理解。

>>> s = [(3, 4), (1, 2)] 
>>> [i for sub in s for i in sub] 
[3, 4, 1, 2] 
+0

請不要使用'l'作爲變量名稱。它在某些字體中看起來很像'1'。 PEP8甚至提到它。 – 2013-03-01 12:00:46

+0

@gnibbler感謝提醒,修正';)' – Volatility 2013-03-01 12:03:13

0

可以使用減少:

>>> import operator 
>>> reduce(operator.add, [(3,4),(1,2)]) 
(3, 4, 1, 2) 
+0

爲什麼這會得到downvoted?僅僅因爲它返回一個元組而不是一個列表? – 2013-03-01 10:34:31

+0

@ Juniper它可能是因爲reduce在Python 3000中已被棄用。猜猜這取決於你使用的是什麼版本。 http://www.artima.com/weblogs/viewpost.jsp?thread=98196 – 2013-03-01 10:39:44

+0

@ Juniper我猜你知道,但你可以將輸出轉換爲列表(reduce(...)) – 2013-03-01 10:41:20