1

Given a list of URLs urls of unknown length, I want to divide it into slices of 20 urls (plus the slice containing the remainder, if there is one). So if it contains 96 URLS, I'll have a 4 slices of 20, and a slice of 16. Also if the length is less than 20, obviously the list itself is the only slice.

Given:

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

Then:

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

From here, I can start constructing the individual slices. But it's all starting to feel a little convoluted. Is there a more efficient (perhaps with NumPy) way of achieving this?

Pyderman
  • 14,809
  • 13
  • 61
  • 106

1 Answers1

4

Slicing is really easy:

>>> 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]]
Patrick Maupin
  • 8,024
  • 2
  • 23
  • 42