[英]insert element in a list after every 2 element
I have this code:我有这个代码:
l = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0]
def add(l, n):
lret = l.copy()
i = n
while i <= len(lret):
lret.insert(i, 0.0)
i += (n+1)
return lret
lret = add(l,2)
print(lret)
Is a way to make the add()
function a one-line function?是一种使
add()
函数成为单行函数的方法吗?
You can use zip()
to build tuples that contain n
elements from the original list with an added element, and then use chain.from_iterable()
to flatten those tuples into the final list:您可以使用
zip()
构建包含原始列表中的n
元素并添加元素的元组,然后使用chain.from_iterable()
将这些元组展平到最终列表中:
from itertools import repeat, chain
def add(lst, n):
return list(chain.from_iterable(zip(*(lst[s::n] for s in range(n)), repeat(0.0))))
This outputs:这输出:
[1.0, 2.0, 0.0, 3.0, 4.0, 0.0, 5.0, 6.0, 0.0]
Possible solution if you want the whole block in one line:如果您希望将整个块放在一行中,可能的解决方案:
return [x for y in (l[i:i + n] + [0.0] * (i < len(l) - n + 2) for
i in xrange(0, len(l), n)) for x in y]
Gives the same output给出相同的输出
[1.0, 2.0, 0.0, 3.0, 4.0, 0.0, 5.0, 6.0, 0.0]
[1.0, 2.0, 0.0, 3.0, 4.0, 0.0, 5.0, 6.0, 0.0]
Found another way to do it:找到了另一种方法:
def add(l,n=2):
return [item for sublist in [(e,) if i % n == 0 or i == 0 else (e, 0.0) for i, e in enumerate(l)] for item in sublist]
[1.0, 2.0, 0.0, 3.0, 4.0, 0.0, 5.0, 6.0, 0.0]
[1.0, 2.0, 0.0, 3.0, 4.0, 0.0, 5.0, 6.0, 0.0]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.