gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 16:26:04 24 4
gpt4 key购买 nike

我遇到了一个问题,涉及将列表拆分为不同大小的 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com