我有這個代碼:
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)
是一種使add()函式成為單行函式的方法嗎?
uj5u.com熱心網友回復:
您可以使用添加元素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))))
這輸出:
[1.0, 2.0, 0.0, 3.0, 4.0, 0.0, 5.0, 6.0, 0.0]
uj5u.com熱心網友回復:
如果您希望將整個塊放在一行中,可能的解決方案:
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]
給出相同的輸出
[1.0, 2.0, 0.0, 3.0, 4.0, 0.0, 5.0, 6.0, 0.0]
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/478448.html
