我在挣扎list comprehensions
。我需要编写一个函数,为每 N 个数字添加 0。该函数如下所示:
def makeSpace(list, space):
list = [list.insert(i, 0) for i in list if ....]
return list
例如,我通过makeSpace(list,2)
,如果我的列表看起来像:1,2,3,4,5,6
那么在函数之后应该返回1,2,0,3,4,0,5,6,0
有人可以告诉我如何制作吗?
PS:如果 for 循环更适合它,它可以是传统的,for loop
我在一个duplicate
问题中找到了一些东西并自行更改:
def fun(lst, space):
i = space
while i < len(lst):
lst.insert(i, 0)
i += space+ 1
return lst
但它不会在末尾添加数字,例如每 3 个空格:[1, 2, 3, 0, 4, 5, 6]
它也应该在 6 之后添加我应该更改什么?
这是一个带有简单 for 循环和一个可递增的独立计数器的版本:
test = [1, 2, 3, 4, 5, 6]
idx = 1
new = []
for num in test:
new.append(num)
if idx % 3 == 0:
new.append(0)
idx += 1
print(new)
[1, 2, 3, 0, 4, 5, 6, 0]
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句