我正在尝试用 Python 做一些简单的事情。我有点生疏了,所以我不确定我做错了什么。我想为字典项目赋予随机值。我想从原始值中减去每个循环,因此如果房子有 5 个房间,那么字典中组合项目的总数不会超过 5。
这不是家庭作业。我从事 IT 工作,我正在尝试练习 Python,这是我所知较弱的脚本语言之一。
在终端中进行简化,它似乎可以工作,但是当我将其放入代码中时,我收到错误。
终端:
$ python3
Python 3.6.8 (default, Apr 25 2019, 21:02:35)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-36)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import random
>>> h1 = random.randint(1,5)
>>> size = random.randint(1, h1)
>>> h1 = h1 - size
>>> print(h1)
2
脚本:
import random
h1 = random.randint(1,5)
rooms = {
"bed" : 0,
"bath": 0,
"study": 0
}
for z in rooms:
size = random.randint(1, h1)
room_types[z] = size
if h1_size != 0:
h1 = h1 - size
for x, y in rooms.items():
print(x, y)
我收到以下错误:
$ ./two.py
Traceback (most recent call last):
File "./two.py", line 13, in <module>
size = random.randint(1, h1)
File "/usr/lib64/python3.6/random.py", line 221, in randint
return self.randrange(a, b+1)
File "/usr/lib64/python3.6/random.py", line 199, in randrange
raise ValueError("empty range for randrange() (%d,%d, %d)" % (istart, istop, width))
ValueError: empty range for randrange() (1,1, 0)
最佳答案
在脚本中,您将在 for
循环的每次迭代中使用 h1 - size
重新分配 h1
,并且 if size
恰好是 h1
,因为它是传递给 randint
的上限,h1
将变为 0
code> 赋值后,这样在下一次迭代中,您将有效地调用 random.randint(1, 0)
,其中上限小于下限,这是不允许的,因此会产生上述错误。
关于python - 在 Python 中设置字典值,同时从最大允许总值中减去,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58192211/