Splitting a list into N parts of approximately equal length

前端 未结 30 1760
迷失自我
迷失自我 2020-11-22 16:16

What is the best way to divide a list into roughly equal parts? For example, if the list has 7 elements and is split it into 2 parts, we want to get 3 elements in o

30条回答
  •  梦谈多话
    2020-11-22 16:43

    My solution, easy to understand

    def split_list(lst, n):
        splitted = []
        for i in reversed(range(1, n + 1)):
            split_point = len(lst)//i
            splitted.append(lst[:split_point])
            lst = lst[split_point:]
        return splitted
    

    And shortest one-liner on this page(written by my girl)

    def split(l, n):
        return [l[int(i*len(l)/n):int((i+1)*len(l)/n-1)] for i in range(n)]
    

提交回复
热议问题