2015-05-04 87 views
13

交錯名單我知道我可以交錯兩個Python列表和:固定元素

[elem for pair in zip(*lists) for elem in pair] 

現在我需要交錯列表中包含一個固定的元素:

list = [1, 2, 3, 4] 
# python magic 
output = [1, 0, 2, 0, 3, 0, 4] 

回答

6

一個真正簡單的解決方案是:

[elem for x in list for elem in (x, 0)][:-1] 
+1

我相信這是最簡單和最清晰的解決方案。 – recursive

+0

這種巫術是如何工作的? – aitchnyu

+1

@aitchnyu如果你有嵌套結構'list = [(1,2),(3,4)]'並且你想扁平它,你可以使用'[elem for pair in list for elem in pair]''所以你取每個「對」,然後把兩個「elem」放在一起。在上面的代碼中,您沒有配對,但是您爲原始列表中的每個元素「x」創建了一對'(x,0)',那麼您可以使用與之前相同的策略來平展列表,獲得'[x1,0,x2,0,x3,0]'。然後使用'[:-1]'刪除尾部的'0'。 –

6

您可以嘗試以下itertools魔術:

>>> from itertools import repeat, chain, izip 
>>> l = [1, 2, 3, 4] 
>>> list(chain.from_iterable(izip(l[:-1], repeat(0)))) + l[-1:] 
[1, 0, 2, 0, 3, 0, 4] 
3

Python的sum功能可以在支持除了通過適當地設置參數start任意數據類型一起使用。 (see docs

input = [1, 2, 3, 4] 
fixed = 0 
output = sum([[elem, fixed] for elem in input], [])[:-1] # to drop the last `fixed` 

或者,如果你不喜歡使用加法運算符與列表的想法:

input = [1, 2, 3, 4] 
fixed = 0 
output = [] 
for elem in input: 
    output.extend([elem, fixed]) 
output = output[:-1] 
4
from itertools import izip, repeat 

start = [1, 2, 3, 4] 

print [i for j in izip(start, repeat(0)) for i in j][:-1] 
+0

我注意到這在列表的末尾附加了一個額外的0。 – Shashank

+0

修復它。謝謝。 –

1

你可以使用的functoolsreduce功能。

>>> from functools import reduce 
>>> reduce(lambda x, y: x + [y, 0], [1,2,3,4], [])[:-1] 
[1, 0, 2, 0, 3, 0, 4] 
2
>>> lst = [1, 2, 3, 4] 
>>> newlst = [0]*((len(lst) * 2) - 1) 
>>> newlst[::2] = lst 
>>> newlst 
[1, 0, 2, 0, 3, 0, 4] 

它可能不是一個班輪,但它的作品。此外,我的time tests似乎表明,這是迄今爲止最快的解決方案。在函數形式,這就是:

def interzero(lst): 
    newlst = [0]*((len(lst) * 2) - 1) 
    newlst[::2] = lst 
    return newlst 
1
>>> from itertools import chain 

>>> lst = [1, 2, 3, 4] 
>>> list(chain(*zip(lst, [0]*(len(lst)-1)))) + [lst[-1]] 
[1, 0, 2, 0, 3, 0, 4]