Rai Re
Rai Re

Reputation: 45

How do you divide a list (indefinite length) randomly into 3 subgroups?

Lets say that my program asks a user to input a number indefinitely and I appended it in a list.

#Given Example:
List = [105, 167, 262, 173, 123, 718, 219, 272, 132]

what I wanted to do is to randomly pick any of the numbers so my sample output would be:

first = [105, 262, 173]
second = [167, 123, 132]
third = [718, 219,272]

Having said, since the user input would be indefinite there will be chances that it would be an odd number.

I am currently using random.sample to choose a number from that list and append it in a list, after that I'll append the sub-groups of list to create a list within a list.

Would be a great help if anyone answers, thanks!

Upvotes: 2

Views: 3603

Answers (2)

Madhav Sharma
Madhav Sharma

Reputation: 56

If List is going to remain short such that you can read it into the memory, then you can use [random.shuffle][1]

import random
List = [105, 167, 262, 173, 123, 718, 219, 272, 132]

random.shuffle(List)
first = L[0:3]

Now use List Comprehension to subtract the original List with first

newList = [item for item in List if item not in first]

Now use newList for second and third and you'd be good to go! :)

Upvotes: 0

Eric Duminil
Eric Duminil

Reputation: 54303

You could shuffle your list with random.shuffle:

>>> import random
>>> l = [105, 167, 262, 173, 123, 718, 219, 272, 132]
>>> random.shuffle(l)
>>> l
[167, 123, 173, 718, 262, 272, 105, 219, 132]

And extract 3 sub-lists with slicing. The first list will have indices 0, 3 and 6 from the shuffled l, the second list will have indices 1, 4 and 7 and the third will have indices 2, 6 and 8:

>>> l[::3]
[167, 718, 105]
>>> l[1::3]
[123, 262, 219]
>>> l[2::3]
[173, 272, 132]

As a bonus, it will work with lists of any length:

>>> l = [1, 2, 3, 4, 5]
>>> random.shuffle(l)
>>> [l[x::3] for x in range(3)]
[[2, 4], [1, 5], [3]]

You can be sure that every element will appear exactly once in the nested lists.

You could also define more sublists:

>>> l = list(range(20))
>>> n = 5
>>> random.shuffle(l)
>>> [l[x::n] for x in range(n)]
[[5, 18, 9, 4], [11, 12, 1, 15], [13, 3, 6, 8], [17, 0, 14, 2], [10, 16, 7, 19]]

Upvotes: 7

Related Questions