Rahul Dev
Rahul Dev

Reputation: 612

Add contents from one list to multiple other lists of variable sizes without repetition

Say I have a list of items:

l1 = ['a','b','c',d','e','f','g']

Now, what I wish to do is to randomly split the contents of this list into n number of lists (say n=3), with well defined sizes (say l2 is of length 3, l3 is also of length 3 and l4 is of length 1) such that none of the elements are repeated. i.e

l2 = ['a','d','e']
l3 = ['b','f',g']
l4 = ['c']

How can such a thing be achieved? Thanks.

Upvotes: 0

Views: 50

Answers (2)

Himaprasoon
Himaprasoon

Reputation: 2659

This works for any number n <= length of list

import random


def get_random_sublist(n, li):
    random.shuffle(l1)
    start = 0
    for k in range(n - 1, 0, -1):
        tmp = random.randrange(start + 1, len(li) - k + 1)
        yield li[start:tmp]
        start = tmp
    yield l1[start:]


l1 = ['a', 'b', 'c', 'd', 'e', 'f', 'g']

for i in get_random_sublist(3, l1):
    print(i)

Output:

['d', 'b']
['c']
['f', 'g', 'a', 'e']

Upvotes: 0

user94559
user94559

Reputation: 60143

One approach would be to randomly shuffle the list and then split it into the sizes you want:

import random

l1 = ['a', 'b', 'c', 'd','e','f','g']

# put the list into a random order
random.shuffle(l1)

l2 = l1[:3]  # first three elements
l3 = l1[3:6]  # second three elements
l4 = l1[6:]  # final element

print(l2)
print(l3)
print(l4)

# Sample output:
# ['d', 'e', 'a']
# ['g', 'b', 'c']
# ['f']

Upvotes: 2

Related Questions