Sorting out lists into nested lists

Viewed 60

I am trying to figure out how to append elements from the list into a pattern where I put them into the nested lists.

For example:

members = [1, 2, 3, 4, 5, 6, 7, 8, 9]
no_of_teams = int(input('no. of teams? '))
teams = [ [ ] for _ in range(no_of_teams)]

So that my output will end up looking like this:

no_of_teams? 2

teams = [ [1, 3, 5, 7, 9], [2, 4, 6, 8]]

if the user enters 3 then it will look like this:

teams = [[1, 4, 7], [2, 5, 8], [3, 6, 9]]

and for 7 it looks like

teams = [ [1, 8], [2, 9], [3], [4], [5], [6], [7] ]
4 Answers

A good way is to use slicing:

number = int(input(...))
members = list(range(1, 10))
chunks = len(members) // number
teams = [members[i*chunks:i*chunks+number]
         for i in range(number)]

You could also use step size instead:

teams = [members[i::number]
         for i in range(number)]

This will yield your desired output:

  • in each iteration, we start the slice at the next item in the list
  • the slice goes up in n steps

So, if n is 3, the 1st iteration will give a slice containing the indexes 0, 3, 6, 9..... since the step size is 3 The 2nd iteration gives indexes 1, 4, 7... The 3rd iteration gives indexes 2, 5, 8... Iteration stops here at the 3rd since n dictates this too.

You can slice it into the correct number of sublists:

slice_size = int(len(members) / no_of_teams)
teams = []
for i in range(no_of_teams):
    teams.append( members[i * slice_size: i * slice_size + slice_size]

Given there are n teams, we can use list comprehension to construct n slices, such that the i-th element is assigned to the i mod n-th team:

teams = [ members[i::n] for i in range(n) ]

For example:

>>> n= 1
>>> [ members[i::n] for i in range(n) ]
[[1, 2, 3, 4, 5, 6, 7, 8, 9]]
>>> n= 2
>>> [ members[i::n] for i in range(n) ]
[[1, 3, 5, 7, 9], [2, 4, 6, 8]]
>>> n= 3
>>> [ members[i::n] for i in range(n) ]
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]

You can slice the list:

teams = [members[i::no_of_teams] for i in range(no_of_teams)]
Related