如何有效地将Python列表切割成20 +一个切片的剩余部分?

时间:2015-09-08 20:54:48

标签: python list numpy indexing slice

鉴于长度未知的list个网址urls,我想将其划分为20个网址的切片(加上包含剩余部分的切片,如果有的话)。因此,如果它包含96个URL,我将有4个20的切片和16个切片。如果长度小于20,显然列表本身是唯一的切片。

鉴于:

quotient = len(urls) / 20
remainder = len(urls) % 20

然后:

if len(urls) / 20 == 0:
   slice = urls
else:
   numberOfSlices = (quotient + 1) if remainder !=0 else quotient

从这里开始,我可以开始构建单个切片。但它开始感到有点复杂。是否有更高效(可能采用NumPy)方式实现这一目标?

1 个答案:

答案 0 :(得分:4)

切片非常简单:

>>> x = list(range(96))
>>> y = [x[i:i+20] for i in range(0, len(x), 20)]
>>> y
[[0, 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]]