Python 中最有效、最可靠的分割扇区的方法是什么:
数量:101(当然可能会有所不同) chunk1:1 到 30 chunk2:31 到 61 chunk3:62 到 92 chunk4:93 到 101
流程:复制扇区 1 到 30,跳过块 1 中的扇区,并从扇区 31 开始复制 30 个扇区。依此类推...
我使用模块和基本数学以“手动”方式解决了这个问题,但是必须有一个函数吗?
谢谢。
小智 3
我假设您将拥有列表格式的数字。因此,在这种情况下,如果您想要非常具体的数字序列簇格式,并且您知道它应该在哪里分开,那么使用索引是最好的方法,因为它的时间复杂度较低。因此,您始终可以创建一个小代码并将其设为可重复使用的函数。像下面这样:
def sectors(num_seq,chunk_size=30):
...: import numpy as np
...: sectors = int(np.ceil(len(num_seq)/float(chunk_size))) #create number of sectors
...: for i in range(sectors):
...: if i < (sectors - 1):
...: print num_seq[(chunk_size*i):(chunk_size*(i+1))] #All will chunk equal size except the last one.
...: else:
...: print num_seq[(chunk_size*i):] #Takes rest at the end.
Run Code Online (Sandbox Code Playgroud)
现在,每次您想要类似的东西时,您都可以重用它,并且它很有效,因为您定义列表索引值而不是搜索它。
这是输出:
x = range(1,101)
print sectors(x)
[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, 30]
[31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60]
[61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90]
[91, 92, 93, 94, 95, 96, 97, 98, 99, 100]
Run Code Online (Sandbox Code Playgroud)
请告诉我这是否满足您的要求。