Splitting a list into N parts of approximately equal length

前端 未结 30 1629
迷失自我
迷失自我 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条回答
  •  萌比男神i
    2020-11-22 17:00

    #!/usr/bin/python
    
    
    first_names = ['Steve', 'Jane', 'Sara', 'Mary','Jack','Bob', 'Bily', 'Boni', 'Chris','Sori', 'Will', 'Won','Li']
    
    def chunks(l, n):
    for i in range(0, len(l), n):
        # Create an index range for l of n items:
        yield l[i:i+n]
    
    result = list(chunks(first_names, 5))
    print result
    

    Picked from this link, and this was what helped me. I had a pre-defined list.

提交回复
热议问题