简体   繁体   English

从列表中选择第n个值,然后在它们之间替换值

[英]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. 我在python中有一个列表,其中包含一些值:List = [0,1,2,3,4,5,6,7,8,9,1,2,3,4,5,6,7,8, 9,...,n]我想做的是选择第n个值,并用零填充它们之间的距离。 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. 这样我最终得到以下列表:结果= [0,0,0,0,0,5,0,0,0,0,0,0,0,0,5,0,0,0,0,.. 。,n]注意:并不总是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): 您可以将第n个项目存储在单独的变量中,然后将整个列表分配给填充值,然后填充存储的列表(这不会创建原始列表的副本):

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 您可以遍历列表,如果索引+ 1不能除以N,则将该项目的值设置为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 您可以使用列表理解来执行此操作,其中x是您的输入列表,n是您要替换的列表的索引

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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