Ser*_*nko 2 python replace list slice
我需要实现 Eratosthenes 算法的筛分。我有列表:
bar = [2, 3, 4, 5, 6, 7, 8, 9, 10]
我需要用“0”替换每个奇数元素。现在我有代码:
while viewIndex < maxNumber:
bar[viewIndex] = 0
viewIndex += 2
Run Code Online (Sandbox Code Playgroud)
但我记得切片。对我来说,写这样的东西会很好:
bar[currentIndex::2] = 0
Run Code Online (Sandbox Code Playgroud)
但我有错误:
TypeError: must assign iterable to extended slice
Run Code Online (Sandbox Code Playgroud)
也许你知道这个任务的一个很好的解决方案。
您应该将切片分配给与赔率数量相同长度的迭代:
bar[1::2] = [0]*(len(bar)//2)
print(bar)
# [2, 0, 4, 0, 6, 0, 8, 0, 10]
Run Code Online (Sandbox Code Playgroud)
要将其扩展为偶数索引,您需要通过添加列表长度的模 2 值来考虑具有奇数长度的列表(与上述情况无关):
bar[::2] = [0]*(len(bar)//2 + len(bar)%2)
Run Code Online (Sandbox Code Playgroud)
这与:
bar[::2] = [0]*sum(divmod(len(bar), 2))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2880 次 |
| 最近记录: |