本文介绍了如何将一个列表分成另一个列表指定的不同大小的卡盘?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个数组,试图将其拆分成不同大小的块.
I have an array I am trying to split into chunks of different sizes.
在下面的示例中,loopN
是卡盘尺寸.我尝试了各种方法来遍历loopN
,但是无法弄清楚. list
是我要拆分为大块的数组.
In the example below, loopN
is are the chuck sizes. I have tried all sorts of ways to iterate through loopN
, however can't figure it out. list
is the array I am trying to split into chunks.
loopN = [2,3,1]
list = [1,2,3,4,5,6]
for i in range(0, len(list), loopN):
chunks.append(list[i:i+loopN])
我想要的输出是[[1,2],[3,4,5],[6]]
.
如何将阵列分成大小不同的卡盘?
How do I split the array into chucks of different sizes?
推荐答案
,您需要遍历loopN
列表,而不是list
.然后,您可以获取列表的相应部分.
you need to loop over the loopN
list, not list
. Then you can get the appropriate slice of the list.
为了避免使用内置关键字,我在下面将list
重命名为l
.
I've renamed list
to l
below, to avoid using a built-in keyword.
i = 0
chunks = []
loopN = [2,3,1]
l = [1,2,3,4,5,6]
for chunksize in loopN:
chunks.append(l[i:i+chunksize])
i += chunksize
这篇关于如何将一个列表分成另一个列表指定的不同大小的卡盘?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!