[英]Skipping n elements iteratively while slicing a list in python
I have a big array of 10573 elements and I want to group them into chunks but skipping two elements after each chunk.我有一个包含 10573 个元素的大数组,我想将它们分组为块,但在每个块之后跳过两个元素。
I have the code to divide the list into chunks:我有将列表分成块的代码:
chunk_size= 109
for i in range(0, len(ints), chunk_size):
chunk = ints[i:i+chunk_size]
But how do I skip or delete two elements from the big list iteratively, ie, after attaining each chunk of size 109?但是我如何迭代地跳过或删除大列表中的两个元素,即在达到每个大小为 109 的块之后?
Is there a way to do that?有没有办法做到这一点?
Add 2 to the chunk size when using it in the iteration.在迭代中使用时将块大小加 2。
chunk_size= 109
for i in range(0, len(ints), chunk_size+2):
chunk = ints[i:i+chunk_size]
Use modular arithmetics:使用模运算:
blocksize = chuncksize + 2
newints = [i for i in ints if i%blocksize < chuncksize]
The other way is to loop backward:另一种方法是向后循环:
blocksize = chuncksize + 2
for i in range(len(ints), 0, -blocksize)
ints.pop(i+chuncksize)
ints.pop(i+chuncksize+1)
Note: Did not test.注意:没有测试。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.