假设我有一个整数n
,我需要将其分区为k
大小的范围,以便结果是这样的元组列表:
[(0, k - 1), (k, 2*k - 1), ...]
如何在python中优雅地完成这项工作?我不询问如何在此处对列表进行分区,我询问如何对整数进行分区,并且只获取列表中范围的起始和最后索引。
答案 0 :(得分:0)
range()
函数需要第三个step
参数:
>>> for i in range(0,15,3):
>>> print(i)
...
... 0
3
6
9
12
您可以将其用作元组的底部,并添加k
或k-1
以获得顶部。
list_of_tuples = []
for i in range(0,n,k):
list_of_tuples.append( tuple(i, i+k-1) )
如果您愿意,可以通过理解来反转:
lot = [ (i,i+k) for i in range(0,n,k) ]
(如果您要将这些数字输入range()
,则不减去一个是个好主意。)
答案 1 :(得分:0)
>>> def gen_include_n(n, k):
... a = zip(range(0, n + 1, k), range(k - 1, n + k, k))
... a[-1] = (a[-1][0], min(n, a[-1][1]))
... return a
...
>>> gen_include_n(10,1)
[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6), (7, 7), (8, 8), (9, 9), (10, 10)]
>>> gen_include_n(10,2)
[(0, 1), (2, 3), (4, 5), (6, 7), (8, 9), (10, 10)]
>>> gen_include_n(10,6)
[(0, 5), (6, 10)]
>>> gen_include_n(10,10)
[(0, 9), (10, 10)]
>>> gen_include_n(10,11)
[(0, 10)]
>>> def gen_exclude_n(n, k):
... a = zip(range(0, n, k), range(k - 1, n + k - 1, k))
... a[-1] = (a[-1][0], min(n - 1, a[-1][1]))
... return a
...
>>> gen_exclude_n(10,1)
[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6), (7, 7), (8, 8), (9, 9)]
>>> gen_exclude_n(10,2)
[(0, 1), (2, 3), (4, 5), (6, 7), (8, 9)]
>>> gen_exclude_n(10,6)
[(0, 5), (6, 9)]
>>> gen_exclude_n(10,10)
[(0, 9)]
>>> gen_exclude_n(10,11)
[(0, 9)]