简体   繁体   中英

Select every nth value from list and replace values between them

I have a list in python, containing some values: List = [0,1,2,3,4,5,6,7,8,9,1,2,3,4,5,6,7,8,9, ...,n] Want I want to do is select every nth value, and fill up the distance between them with zeros. Such that I end up with following list: Result = [0,0,0,0,5,0,0,0,0,0,0,0,0,5,0,0,0,0, ...,n] Note: It's not always a 5.

What I've done: Writing something like a windowing function and iterate through the list.

def window(x):
    window = []
    for ii in range(len(x)):
        mask = [0,1,2,3,None,5,6,7,8]
        select = [x is None for x in mask]
        center = list(itertools.compress(x[ii],select))
        window.append(center)
        for ii in range(0,4):
            center.insert(0,"0")
            center.append("0")
    return window

This Function works, but some how stops after the first iteration and I don't know why.

You can store every n'th item in a separate variable, then assign the whole list to the fill value and then fill back the stored ones (this won't create a copy of the original list):

import itertools as it

l = list(range(20))
tmp = l[::5]
l[:] = it.repeat(0, len(l))
l[::5] = tmp

If you are fine with making a copy then you can also use the following:

l = list(range(20))
l = [0 if i % 5 else x for i, x in enumerate(l)]

you can just iterate through the list and if the index + 1 is not divisable by N then set the value of that item to 0

data = list(range(1,30))
print(data)
n_param = 5
for i in range(len(data)):
    if (i+1) % n_param:
        data[i] = 0
print(data)

output

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29]
[0, 0, 0, 0, 5, 0, 0, 0, 0, 10, 0, 0, 0, 0, 15, 0, 0, 0, 0, 20, 0, 0, 0, 0, 25, 0, 0, 0, 0]

You can do this using a list comprehension where x is your input list and n is index of list where you want to replace

def window(x, n):
   output = [n if (i+1)%n == 0 and i!=0 else 0 for i, item in enumerate(x)]
   return output

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM