我知道我可以将两个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]
答案 0 :(得分:7)
一个非常直接的解决方案是:
[elem for x in list for elem in (x, 0)][:-1]
答案 1 :(得分: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]
答案 2 :(得分: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]
答案 3 :(得分: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 :(得分: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
答案 5 :(得分:1)
您可以使用reduce
的{{1}}功能。
functools
答案 6 :(得分: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]