- A+

Category：Languages

Suppose I have the following list in Python:

`my_list = [10] * 95 `

Given `n`

, I want to replace any other `m`

elements with zero in my list, while keeping the next `n`

elements.

For example, if `n = 3`

and `m = 2`

, I want my list to look like:

`[10, 10, 10, 0, 0, 10, 10, 10 ,0, 0, ..., 10, 10, 10 , 0, 0] `

If it can't be filled perfectly, as is the case with `n = 4`

and `m = 2`

, then it's OK if my list looks like this:

`[10, 10, 10, 10, 0, 0, ..., 10, 10, 10, 10, 0] `

How should I try to solve this problem?

`my_list = [10] * 95 n = 3 m = 2 for i in range(m): my_list[n+i::m+n] = [0] * len(my_list[n+i::m+n]) `

If you really just have two possible values (e. g. 10 and 0), you can do it even simpler:

`my_list = [ 10 if i % (n+m) < n else 0 for i in range(95) ] `

A bit more complex but probably more efficient (especially for huge lists and large values for `n`

and `m`

) would be this:

`my_list = (([ 10 ] * n + [ 0 ] * m) * (95 // (n + m) + 1))[:95] `