交错名单我知道我可以交错两个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]
交错名单我知道我可以交错两个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]
一个真正简单的解决方案是:
[elem for x in list for elem in (x, 0)][:-1]
您可以尝试以下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]
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]
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。 – Shashank
修复它。谢谢。 –
你可以使用的functools
的reduce
功能。
>>> from functools import reduce
>>> reduce(lambda x, y: x + [y, 0], [1,2,3,4], [])[:-1]
[1, 0, 2, 0, 3, 0, 4]
>>> 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
>>> 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]
我相信这是最简单和最清晰的解决方案。 – recursive
这种巫术是如何工作的? – aitchnyu
@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'。 –