2

Given the following list:

l1 = [0,1000,5000,10000,20000,30000,40000,50000]

I know I can create chunks of it by looking at every consecutive pair of numbers:

def chunker(seq, size):
    return (seq[pos:pos + size] for pos in range(0, len(seq), size))

for group in chunker(l1, 2):
   print(group)

This returns:

[0, 1000]
[5000, 10000]
[20000, 30000]
[40000, 50000]

How can I make sure that overlapping intervals, such as [1000,5000], are also included?

Expected output:

[0, 1000]
[1000, 5000] 
[5000, 10000]
[10000, 20000]
[20000, 30000]
[30000, 40000]
[40000, 50000]
Zizzipupp
  • 1,301
  • 1
  • 11
  • 27

4 Answers4

6

One way is using a list comprehension with zip:

[[i,j] for i,j in zip(l1[:-1], l1[1:])]

[[0, 1000],
 [1000, 5000],
 [5000, 10000],
 [10000, 20000],
 [20000, 30000],
 [30000, 40000],
 [40000, 50000]]

Or using your approach, but setting a step of 1 (which is also the default step size) in the range:

def chunker(seq, size):
    return (seq[pos:pos + size] for pos in range(0, len(seq), 1))

for group in chunker(l1, 2):
    print(group)

[0, 1000]
[1000, 5000]
[5000, 10000]
[10000, 20000]
[20000, 30000]
[30000, 40000]
[40000, 50000]
[50000]
yatu
  • 86,083
  • 12
  • 84
  • 139
6

You unnecessarily iterate over range with the step size. This way you prevent groups starting in place where the other group finishes. This code should work:

l1 = [0,1000,5000,10000,20000,30000,40000,50000]

def chunker(seq, size):
    return (seq[pos:pos + size] for pos in range(0, len(seq)))

for group in chunker(l1, 2):
   print(group)

The output is:

[0, 1000]
[1000, 5000]
[5000, 10000]
[10000, 20000]
[20000, 30000]
[30000, 40000]
[40000, 50000]
[50000]

You may skip the last element if that is what you wish, but depends on your requirement.

Joanna
  • 271
  • 1
  • 9
4
l1 = [0,1000,5000,10000,20000,30000,40000,50000]

def chunker(seq, size):
    return ([seq[i], seq[i+1]] for i in range(len(seq)) if i<len(seq)-1)

for group in chunker(l1, 2):
   print(group)

# result:
[0, 1000]
[1000, 5000]
[5000, 10000]
[10000, 20000]
[20000, 30000]
[30000, 40000]
[40000, 50000]
Frank
  • 1,959
  • 12
  • 27
3

Hi you just have to delete the footstep:

def chunker(seq, size):
    return (seq[pos:pos + size] for pos in range(0, len(seq)))

for group in chunker(l1, 2):
   print(group)


[1000, 5000]
[5000, 10000]
[10000, 20000]
[20000, 30000]
[30000, 40000]
[40000, 50000]
[50000]
Jad
  • 109
  • 10