Shaun Han
Shaun Han

Reputation: 2785

Split a list randomly given chunk sizes in python

I want to write a function that returns a list of randomly splitted chunks, given a list of sizes of each chunk. For example, say I have a list of unique integers from 0 to 9

lst = list(range(10))

I want to split into 4 chunks of sizes 1, 2, 2 and 5, so the function should take an input variable sizes as below:

my_func(lst, sizes=[1, 2, 2, 5])

I expect the function to return something like

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

If the input sizes = [5, 1, 4], I expect the function to return something in order like

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

Any suggestions?

Upvotes: 1

Views: 619

Answers (3)

Vivek G.
Vivek G.

Reputation: 51

you can do something like this:

import random

lis=[]
g_lis=[]

for i in sizes:
    list_int = i

    for j in range(list_int):
        num = random.randint(0,9)
        lis.append(num)

    g_lis.append(lis)

Upvotes: 0

Kuldeep Singh Sidhu
Kuldeep Singh Sidhu

Reputation: 3856

My approach is to use random.shuffle and then go through the shuffled array!

import random
def my_func(lst, sizes):
    random.shuffle(lst)
    ret = []
    pointer = 0
    for s in sizes:
        ret.append(lst[pointer:pointer+s])
        pointer+=s
    return ret

lst = list(range(10))
print(my_func(lst, sizes = [1, 2, 2, 5]))
print(my_func(lst, sizes = [5, 1, 4]))
[[5], [6, 7], [4, 0], [8, 3, 9, 2, 1]]
[[5, 2, 4, 3, 0], [8], [6, 7, 9, 1]]

Upvotes: 2

Abdul Aziz Barkat
Abdul Aziz Barkat

Reputation: 21807

Use random.shuffle to shuffle your list. Also just keep slicing the list.

import random

def random_split(lst, sizes):
    if sum(sizes) != len(lst):
        raise ValueError("Sizes should match list length!")
    lst = lst.copy() # Copy list
    random.shuffle(lst) # shuffle
    res = []
    for size in sizes:
        split_list, lst = lst[:size], lst[size:] # Make two pieces of the list
        # split_list.sort()
        # Above line should be used if each sublist should be sorted
        res.append(split_list)
    return res

Upvotes: 0

Related Questions