0

My question is this:

If for example we have a list of numbers in order from 1 to 1200 like: 1,2,3,4,5,...,1200 How can we extract for a specific size (lets say 400) the following chunks in python: 1-400, 200-600, 400-800, 600-1000, 800-1200

what i made so far is this:

a = [i for i in range(1200)]
swift_number = 400
num1 = 0
num2 = num1 + swift_number
while (len(a) - num1) > swift_number:
    print "getting numbers from %s to %s", num1, num2
    num1 = num2 - swift_number / 2
    num2 = num1 + swift_number
Giorgos Perakis
  • 153
  • 2
  • 12
  • You can use slicing notation: http://stackoverflow.com/questions/509211/explain-pythons-slice-notation. Like a[0:400] if I get understand you. – alpert Nov 03 '15 at 12:29
  • 2
    As a sidenote: `[i for i in range(1200)]` → `list(range(1200))` – spectras Nov 03 '15 at 12:31

3 Answers3

2

Taking advantage of slice notation, it is possible to simplify a lot:

a = list(range(1200))
swift_number = 400          # how many items per chunk
step = int(swift_number/2)  # how many items we shift for each chunk

chunks = [
    a[base:base+swift_number]
    for base in range(0, len(a), step)
]

That makes chunks be a list of lists. First list has items [0..399], second list has items [200..599], third list has items [400..799] and so on.

This can be put on a single line:

chunks = [a[base:base+swift_number] for base in range(0, len(a), step)]
spectras
  • 13,105
  • 2
  • 31
  • 53
1

in order to address sub-lists, use ranged indices:

x=[10, 20, 30, 40, 50, 60]
y=x[2:4] ## evaluates to [30, 40, 50]

so your code would look like:

a=list(range(1, 1200+1))
width=400
for slice in range(2*len(a)/width - 1):
   index=slice*width/2
   print("%s" % (a[index:index+width]))
umläute
  • 28,885
  • 9
  • 68
  • 122
1

This is my solution using itertools.groupby

import itertools

[list(g) for _, g in itertools.groupby(xrange(1, 1201), lambda x: not(x % 400))]
sardok
  • 1,086
  • 1
  • 10
  • 19