gpt4 book ai didi

python - 在 Python 中以随机大小的部分拆分数字

转载 作者:行者123 更新时间:2023-11-28 17:36:27 27 4
gpt4 key购买 nike

我有 x = 10y = 100

我可以将 y 元素随机分配给 x “元素持有者”吗?

我想创建 x 个类别,每个类别都有随机数量的项目;但是,创建的项目数应该正好是 y

我猜是这样的

# number of categories and items
x = 10, y = 100

# keep track of how many items we have left to add
y_left = y

# create all categories
for i in range(x):
# create category

# find number of items in this category
num_items_in_category = random.randint(1, y_left)

# create items
for j in range(num_items_in_category):
# create item

# set new number of items left to add
y_left -= num_items_in_category

最佳答案

这其实并不难。让我们创建我们的容器:

import random

num_containers = 10
num_objects = 100

containers = [[] for _ in range(num_containers)]
objects = (some_object() for _ in range(num_objects))
# we don't need a list of these, just have to iterate over it, so this is a genexp

for object in objects:
random.choice(containers).append(object)

关于python - 在 Python 中以随机大小的部分拆分数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30004442/

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