python - 将列表随机分成两个或三个项目的 block

标签 python list random chunks

我遇到了一个问题,涉及将列表拆分为不同大小的 block 。我想要一个随机分成 2 对或 3 对的列表。

例子:

L = [1,1,1,1,1,1,1,1,1,1,1,1]

我想得到一些东西:

L2 = [(1,1,1),(1,1),(1,1),(1,1,1),(1,1)]

但我希望它是随机的,以便每次运行代码时成对和三元组的分布都会发生变化。

最佳答案

作为更通用的方法,您可以使用以下函数:

from itertools import count
import random
def my_split(lst, chunks):
    def chunk_creator():
        total = 0
        while total <= len(lst):
            x = random.choice(chunks)
            yield L[total: x + total]
            total += x
        yield total - x

    def chunk_finder():
        for _ in count():
            chunk = list(chunk_creator())
            total = chunk.pop(-1)
            if total == len(L):
                return chunk[:-1]
    if max(chunks) <= len(L):
        return chunk_finder()
    else:
        return None

演示:

>>> L = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] 
>>> my_split(L, (2, 3))
... [[1, 1], [1, 1], [1, 1], [1, 1, 1], [1, 1, 1]]
>>> my_split(L, (2, 3))
... [[1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1]]

说明:

此功能由子功能组成。第一个是 chunk_creator,它的工作是根据列表的长度创建所需的 block ,并将它们作为迭代器返回。请注意,最终值是 total 变量,它是前面 block 的总和。

第二个函数 (chunk_finder) 将通过无限循环 (itertools.count()) 并检查total 等于输入列表的长度。

关于python - 将列表随机分成两个或三个项目的 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36498648/

相关文章:

c++ - C++ 应用程序中的 PyQt4 插件

list - 生成一个保证其中有 7 的列表

c++ - 生成0到1之间的随机数

python - python中这个 "POST for loop"是怎么回事? ——Python菜鸟

python - 用于数据库目的的最合适的 .mat 文件转换

java - 从区间中排除数字,检索其余数字

list - 将列表放入方案的参数中

php - 使用 rand 生成确认码安全吗? php

c++ - 试图从一个类中生成随机 int

python - 如何将字典的键与字符串字符进行比较