Skip to content

Instantly share code, notes, and snippets.

@kaniblu
Created April 29, 2020 03:10
Show Gist options
  • Save kaniblu/b3786dbf2a84dd7dc00be5ab5f6fea1a to your computer and use it in GitHub Desktop.
Save kaniblu/b3786dbf2a84dd7dc00be5ab5f6fea1a to your computer and use it in GitHub Desktop.
Split a sequence into chunks closest to the given ratio
from typing import Sequence
import numpy as np
def split_list(items: Sequence, ratios: Sequence[float]):
ratios = np.cumsum(np.array(ratios) / sum(ratios)).tolist()
indices = [0] + [int(round(len(items) * r)) for r in ratios]
return [items[i:j] for i, j in zip(indices, indices[1:])]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment