本文介绍了将列表拆分为随机大小的块的最佳方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数字列表,例如[5000,5000,5000,5000,5000,5000]

I have a list of numbers such as [5000, 5000, 5000, 5000, 5000, 5000]

我需要创建一个函数,将该函数转换为随机大小较小的列表,例如

I need to create a function that turns that list into a list of randomly sized smaller lists, such as

[[5000,5000],[5000,5000,5000],[5000]]

[[5000, 5000], [5000, 5000, 5000], [5000]]

在python中执行此操作的最佳方法是什么?

What's the best way to do this in python?

推荐答案

from itertools import islice
from random import randint

def random_chunk(li, min_chunk=1, max_chunk=3):
    it = iter(li)
    while True:
        nxt = list(islice(it,randint(min_chunk,max_chunk)))
        if nxt:
            yield nxt
        else:
            break

演示:

li = [5000, 5000, 5000, 5000, 5000, 5000]

list(random_chunk(li))
Out[45]: [[5000, 5000, 5000], [5000], [5000, 5000]]

这将导致(忽略最后一个块)在min_chunkmax_chunk之间(包括两端)的块大小均匀分布.

This results in a (ignoring the last chunk) uniform distribution of chunk sizes between min_chunk and max_chunk, inclusively.

这篇关于将列表拆分为随机大小的块的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-10 21:47