作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有 x = 10
和 y = 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/
我是一名优秀的程序员,十分优秀!