如何最有效地替换python中数组的每个第n个值? [英] how to replace every n-th value of an array in python most efficiently?
问题描述
我想知道是否有更pythonic(和有效)的方法来执行以下操作:
I was wondering whether there is a more pythonic (and efficient) way of doing the following:
MAX_SIZE = 100
nbr_elements = 10000
y = np.random.randint(1, MAX_SIZE, nbr_elements)
REPLACE_EVERY_Nth = 100
REPLACE_WITH = 120
c = 0
for index, item in enumerate(y):
c += 1
if (c % REPLACE_EVERY_Nth == 0):
y[index] = REPLACE_WITH
所以基本上我生成了一堆从 1 到 MAX_SIZE-1
的数字,然后我想用 REPLACE_WITH
替换每个 REPLACE_EVERY_Nth
元素.这工作正常,但我想可以在不使用 enumerate
的情况下以某种方式完成?
So basically I generate a bunch of numbers from 1 to MAX_SIZE-1
, and then I want to replace every REPLACE_EVERY_Nth
element with REPLACE_WITH
. This works fine but I guess it could be somehow done without using enumerate
?
我在想这样的事情(我知道这是错误的,因为我用 y 的索引替换了原来的 y):
I was thinking something like this (which I know is wrong, because I replace the original y with the indices of y):
y = map(lambda x: REPLACE_WITH if not x%REPLACE_EVERY_Nth else x, range(len(y)))
有没有办法对索引进行取模但替换值?
is there a way to do modulo on the indices but replace the values?
推荐答案
使用以 REPLACE_EVERY_Nth
作为步长值的切片:
Use a slicing with REPLACE_EVERY_Nth
as step value:
y[::REPLACE_EVERY_Nth] = REPLACE_WITH
这与您的代码略有不同,因为它将从第一个项目(即索引 0)开始.要准确了解您的代码的作用,请使用
This is slightly different from your code, since it will start with the very first item (i.e. index 0). To get exactly what your code does, use
y[REPLACE_EVERY_Nth - 1::REPLACE_EVERY_Nth] = REPLACE_WITH
这篇关于如何最有效地替换python中数组的每个第n个值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!