2

Lets say I have this list of numbers:

1, 2, 3, 4, 7, 8, 10, 12, 15, 16, 17, 18, 19, 20, 21, 22, 24, 26, 27, 29

And I want to create 5 even groups based on ascending order in the list:

group 1: 1, 2, 3, 4, 7

group 2: 8, 10, 12, 15, 16

group 3: 17, 18, 19, 20, 21

etc...

Can I use python to do this? I know that I can group by 0:4; 5:9... but I have many lists of various lengths that I need to sort into 5 exact groups each.

Kactus
  • 142
  • 1
  • 11

3 Answers3

4

You can try this:

l = [1, 2, 3, 4, 7, 8, 10, 12, 15, 16, 17, 18, 19, 20, 21, 22, 24, 26, 27, 29]

new_groups = [l[i:i+5] for i in range(0, len(l), 5)]

Output:

[[1, 2, 3, 4, 7], [8, 10, 12, 15, 16], [17, 18, 19, 20, 21], [22, 24, 26, 27, 29]]

If you want to access each group by number, you can build a dictionary:

accessing = {i+1:a for i, a in zip(range(5), new_groups)}

print(acessing[2])

Output:

[8, 10, 12, 15, 16]
Ajax1234
  • 69,937
  • 8
  • 61
  • 102
2

Sort your list, and then use the grouper recipe from itertools:

from itertools import zip_longest
l = [1, 2, 3, 4, 7, 8, 10, 12, 15, 16, 17, 18, 19, 20, 21, 22, 24, 26, 27, 29]
l.sort()

def grouper(iterable, n, fillvalue=None):
    args = [iter(iterable)] * n
    return zip_longest(*args, fillvalue=fillvalue)

groups = list(grouper(l, 5))
print(groups)
# [(1, 2, 3, 4, 7), (8, 10, 12, 15, 16), (17, 18, 19, 20, 21), (22, 24, 26, 27, 29)]
Christian Dean
  • 22,138
  • 7
  • 54
  • 87
0

You can do that based on the length of the list.

l = [...]
groupLength = len(l) // 5
groups = [l[i*groupLength:(i+1)*groupLength] for i in range(5)]

Then either complete the last group with the remaining elements:

groups[-1].extend(l[-len(l)%5:])

Or simply put the remaining elements into a new group:

groups.append(l[-(len(l)%5):])
Right leg
  • 16,080
  • 7
  • 48
  • 81