我和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循环对它更好,它可以是我在duplicate
中发现的传统for loop
问题,然后自己修改:
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之后添加,我应该更改什么?
发布于 2019-03-13 04:27:39
下面是一个简单的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]
https://stackoverflow.com/questions/55129890
复制相似问题