我需要从线性整数列表(不能从0开始)开始进行“相等”切片,但是要满足以下要求:
- 最后的值(最大值)总是必须出现
- 间隔不得小于步长(最重要的是,在倒数第二个和最后一个值之间)
- 给定上述要点,某些间隔可能比该步骤高,并且这些间隔必须在结果列表之间平均放置
- 仅应使用标准库函数(无numpy)
一些例子:
with a list from
range(10)
and step 2, the result should be one of the following:[0, 2, 5, 7, 9]
[0, 2, 4, 7, 9]
with
range(21)
and step 3:[0, 3, 7, 10, 14, 17, 20]
with
range(1, 22)
and step 3:[1, 4, 8, 11, 15, 18, 21]
现在我有类似的东西,显然不能正常工作:
def getSlices(l, s):
skipCount = (len(l) - 1) % s
divCount = int(len(l) / (skipCount + 1))
o = []
for delta, skip in enumerate(range(skipCount + 1)):
o.extend(l[skip * divCount + delta:(skip + 1) * divCount + delta:s])
return o
>>> getSlices(list(range(21)), 3)
[0, 3, 6, 8, 11, 14, 16, 19]
I know I could just cycle through all values, skip by correlating enumerate
indexes and steps, and add a "delta" as soon as a new "portion" of the list is reached, but that doesn't seem the most performing solution.