Python均分列表

Catalog

将列表均匀切分

备注:此处追求代码简洁,不用math.ceil

total = list(range(19))
print(total)
length = len(total)
n = 4
step = int(length / n) + 1
for i in range(0, length, step):
    print(total[i: i + step])

打印结果

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

应用场景:多进程

def f(ls):
    from time import sleep
    for i in range(len(ls)):
        print(ls.pop(), ls)
        sleep(0.01)
def mult(funct, ls, n=3):
    from multiprocessing import Process
    pool = []  # 进程池
    length = len(ls)
    step = int(length / n) + 1
    for i in range(0, length, step):
        p = Process(target=funct, args=(ls[i: i + step],))
        pool.append(p)
    for p in pool:
        p.start()
    for p in pool:
        p.join()
if __name__ == '__main__':
    mult(f, list(range(17)))

猜你喜欢

转载自blog.csdn.net/Yellow_python/article/details/82387370