【问题标题】:Python. Replace elements using slicePython。使用切片替换元素
【发布时间】:2018-05-17 23:41:25
【问题描述】:

我需要实现埃拉托色尼筛算法。 我有名单:
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

也许你知道这个任务的一个很好的解决方案。

【问题讨论】:

  • 如果您正在寻找构建 Eatosthenes 筛,有一个 here。不知道你仅仅通过跳过奇数索引来完成什么。筛子会为您处理所有事情。
  • numpy 让您可以直接执行此操作。如果核心 python 也这样做会很好。

标签: python list replace slice


【解决方案1】:

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

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))

【讨论】:

  • :: 有什么作用?不熟悉。
  • @pstatix Python 的切片语法:start:stop:stride
  • 您不一定需要使用::,是吗?单个: 将起作用,至少它在@RoachLord 的帖子中是这样显示的。
  • @pstatix 你需要它:切片从索引 1 开始,到末尾(省略,因此连续冒号),步长为 2。等效于 bar[1:len(bar):2]
  • @schwobaseggl 太好了,明白了。
【解决方案2】:

使用简单的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]

【讨论】:

    【解决方案3】:

    您可以使用 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)
    

    【讨论】:

    • 在你的情况下,我将有迭代器。但我需要列表
    • 你用的是什么版本的python?我确定我使用的是 python 2,map 返回 list 类型而不是迭代器。
    • 现在我用的是python 3.5,但是我读过关于python 2的书。非常感谢你的回答!
    • 您可以像list(map(lambda i: 0 if i%2!=0 else i, bar))一样显式地将地图对象转换为列表
    【解决方案4】:

    感谢大家的回答。我的 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
    

    【讨论】:

      【解决方案5】:

      我使用 numpy:

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

      这行得通。

      您不必跟踪索引 - 切片的目的是让事情方便,而不是强迫您跟踪一周中的哪一天相对于第三天上个月的星期二你买了面包。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-08-04
        • 2015-03-02
        • 2020-06-10
        • 2023-04-06
        • 1970-01-01
        • 1970-01-01
        • 2018-08-17
        相关资源
        最近更新 更多