Search code examples
pythonpython-3.xlistsplit

Split a list with a adjustable ratio


so i am trying to create a function that split a list with values with an adjustable ratio.

To just split the list in half i have this function:

def list_splitter(list_to_split):  

    half = len(list_to_split) // 2
    return list_to_split[:half], list_to_split[half:]

Where list_to_split has 1000 objects. But i want to do something like this:

def list_splitter(list_to_split, ratio):

    part1 = len(list_to_split) * ratio
    part2 = 1 - ratio 
    return list_to_split[:part1], list_to_split[part2:]

So for example i want to be able to set ratio = 0.75, so that 0.75% (750 objects) is added in the first part, and 250 in the other part.


Solution

  • Well, something like this should do it:

    def list_splitter(list_to_split, ratio):
        elements = len(list_to_split)
        middle = int(elements * ratio)
        return [list_to_split[:middle], list_to_split[middle:]]