蟒蛇。使用切片替换元素

时间:2017-12-04 13:31:27

标签: python list replace slice

我需要实现Sierat of Eratosthenes算法。 我有清单:
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

也许你知道这项任务的美妙解决方案。

5 个答案:

答案 0 :(得分:4)

您应该将切片分配给与赔率数相同长度的可迭代:

bar[1::2] = [0]*(len(bar)//2)
print(bar)
# [2, 0, 4, 0, 6, 0, 8, 0, 10]

要为偶数索引扩展此值,您需要通过添加列表长度的模2值来考虑具有奇数长度的列表(与上述情况无关):

bar[::2] = [0]*(len(bar)//2 + len(bar)%2)

与...相同:

bar[::2] = [0]*sum(divmod(len(bar), 2))

答案 1 :(得分:0)

使用简单的for循环

bar = [2, 3, 4, 5, 6, 7, 8, 9, 10]
for i in  range(len(bar)):
   if bar[i] % 2 != 0:
       bar[i] = 0
print(bar)

<强>输出

[2, 0, 4, 0, 6, 0, 8, 0, 10]

答案 2 :(得分:0)

您可以使用map将奇数索引上的元素设置为零,

bar = [2, 3, 4, 5, 6, 7, 8, 9, 10]
print map(lambda i: 0 if bar.index(i)%2!=0 else i, bar)

[2, 0, 4, 0, 6, 0, 8, 0, 10]

或者如果你想将奇数元素值设置为零,你可以这样做,

map(lambda i: 0 if i%2!=0 else i, bar)

答案 3 :(得分:0)

感谢所有人的回答。我实现了Eatosthenes Sieve算法:

def resheto(data): 
     print("\tStart Resheto") 
     currentIndex = 0 

     while currentIndex < len(data) - 1: 
         data[currentIndex + data[currentIndex]::data[currentIndex]] = \
             [0] * ((len(data) + 1) // data[currentIndex] - 1) 
         currentIndex += 1 

         while currentIndex < len(data) - 1 and data[currentIndex] == 0: 
             currentIndex += 1 

         if currentIndex >= len(data) - 1: 
             break 
print("\tEnd Resheto") return data

答案 4 :(得分:0)

我使用numpy:

foo = np.ones(10)
foo[1::2] = 2

这行得通。

您不必跟踪索引-切片的目的是使事情变得更方便,而不是强迫您跟踪相对于第三天的星期几您上个月的星期二买了面包。

相关问题