我需要实现埃拉托色尼筛法算法。
我有 list :
bar = [2, 3, 4, 5, 6, 7, 8, 9, 10]
我需要用“0”替换每个奇数元素。
现在我有了代码:
while viewIndex < maxNumber:
bar[viewIndex] = 0
viewIndex += 2
但我记得切片。对我来说,写这样的东西会很好:
bar[currentIndex::2] = 0
但是我有错误:
TypeError: must assign iterable to extended slice
也许您知道这个任务的完美解决方案。
最佳答案
您应该将切片分配给与赔率数长度相同的可迭代对象:
bar[1::2] = [0]*(len(bar)//2)
print(bar)
# [2, 0, 4, 0, 6, 0, 8, 0, 10]
要为 even 索引扩展它,您需要通过添加列表长度的模 2 值来考虑具有奇数长度的列表(与上述情况无关):
bar[::2] = [0]*(len(bar)//2 + len(bar)%2)
这与:
bar[::2] = [0]*sum(divmod(len(bar), 2))
关于Python。使用 slice 替换元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47634525/