5

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

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?

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?

1
  • Can't you just start with 1 and count by 100 (or N)? Commented Mar 20, 2012 at 19:42

3 Answers 3

23

Use a slicing with REPLACE_EVERY_Nth as step value:

y[::REPLACE_EVERY_Nth] = REPLACE_WITH

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
Sign up to request clarification or add additional context in comments.

9 Comments

@Zenon: You can. Try it. And please take back the downvote.
@Zenon: You used a list, not a NumPy array. And even for a list, such an assignment is possible, but you need to assign, well, an iterable.
@Sven Marnach, it works with numpy arrays but not lists, I am really sorry, this is really cool!
@memyself: I included how to use an offset.
@Zenon: With lists, try something like: y[::REPLACE_EVERY_Nth] = itertools.repeat(REPLACE_WITH, nbr_elements//REPLACE_EVERY_Nth)
|
3

You can simply use range(start, end, step) for your loop:

for index in range(0,len(y),REPLACE_EVERY_Nth):
    y[index] = REPLACE_WITH

Comments

1

I think following solution can be applied without having any issues:

for index in xrange(0, len(y), REPLACE_EVERY_Nth):
    y[index] = REPLACE_WITH

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.