把一个list,tuple,set分片

1. 函数

 import math

 def split_list(data, num_page):
    '''
    num_page: 打算分成多少个小列表   int类型
    data: 为一个待分割的列表  list  or tuple or set 类型
    '''
    data_list = list()
    try:
        n = len(data) // num_page
    except Exception as e:
        n = len(data)

    if n == 0:
        n = len(data)

    for i in range(0, len(data), n):
        a = data[i: i + n]
        data_list.append(a)
    return data_list

2. 测试

if __name__ == '__main__':
    a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17]
    result = split_list(a, 3)
    print(result)

结果:
[[1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 12], [13, 14, 15, 16, 17]]

你可能感兴趣的:(把一个list,tuple,set分片)