将 python 数组拆分为大小相等的块,并在索引处省略元素

Split python array into equally-sized chunks and omit elements at indexes

提问人:Enos591 提问时间:10/19/2022 更新时间:10/19/2022 访问量:53

问:

我需要迭代 0-6、30-36、60-66 等索引,并省略两者之间的索引值。

我发现像这样可以拆分为相等的块,但没有找到排除特定索引的方法......

def chunks(xs, n):
n = max(1, n)
return (xs[i:i+n] for i in range(0, len(xs), n))

有人有提示吗?

谢谢,一切顺利

Python 数组 拆分 切片

评论


答:

0赞 Deepak Tripathi 10/19/2022 #1

将函数更改为

def chunks(xs, n):
    steps = 30 # you should also give the steps in your case it is 30
    n = max(1, n)
    return (xs[i:i+n] for i in range(0, len(xs), steps))  # Also this will be returning generator if you want list then use [xs[i:i+n] for i in range(0, len(xs), steps)]