Splitting a list into N parts of approximately equal length

前端 未结 30 1627
迷失自我
迷失自我 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:50

    I've written code in this case myself:

    def chunk_ports(port_start, port_end, portions):
        if port_end < port_start:
            return None
    
        total = port_end - port_start + 1
    
        fractions = int(math.floor(float(total) / portions))
    
        results = []
    
        # No enough to chuck.
        if fractions < 1:
            return None
    
        # Reverse, so any additional items would be in the first range.
        _e = port_end
        for i in range(portions, 0, -1):
            print "i", i
    
            if i == 1:
                _s = port_start
            else:
                _s = _e - fractions + 1
    
            results.append((_s, _e))
    
            _e = _s - 1
    
        results.reverse()
    
        return results
    

    divide_ports(1, 10, 9) would return

    [(1, 2), (3, 3), (4, 4), (5, 5), (6, 6), (7, 7), (8, 8), (9, 9), (10, 10)]
    

提交回复
热议问题