python - 在 Python 中设置字典值,同时从最大允许总值中减去

标签 python python-3.x

我正在尝试用 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/

相关文章:

python - Python中列表,序列和切片之间的区别?

python 木星 : `%run -d` (debug mode) doesn't work

python - 为什么我需要使用 'while' 函数来解决这个问题?

python - 如何打印PCAP文件中的所有目标端口和源端口?

python - 波浪号对 boolean 值的影响——为什么 Python 中的 ~True 是 -2 & ~False 是 -1?

javascript - 在用户输入的 Bokeh 中隐藏绘图 - 自定义 JS?

python - 尝试在 python-slackclient 中使用@channel、@here 和@user

python - 如何在自定义颜色图中获取屏蔽值的透明度 (matplotlib/python)

python - Pandas unstack()和pivot() : MemoryError

python - Python 3 中的 for 循环出现问题 : getting the index in string2 of an element from string1