我刚刚开始学习如何编码,所以这可能看起来是一个愚蠢的问题,但我正在尝试构建一个简单的程序,其中计算机生成一个随机数,并且用户有 1 次机会得到正确的结果。
但是,程序总是卡在这个变量上:
number = np.random.randint(low=1, high=10, size=1)
我不知道这个函数是否不能作为变量(它本身可以工作,但当分配给“number”时不能),但每当我运行它时就会出现:
File "/Users/User/Desktop/Python/App.py", line 4, in <module>
print("The number was " + number)
numpy.core._exceptions.UFuncTypeError: ufunc 'add' did not contain a loop with signature matching types (dtype('<U21'), dtype('<U21')) -> dtype('<U21')```
最佳答案
这里有两个问题。首先 number
不是 int,而是包含 int 的 Numpy 数组。如果你只是省略 size
参数,它会给你一个 int。
number = np.random.randint(low=1, high=10)
其次,您尝试使用 Numpy 数组添加字符串,但这是行不通的。与添加字符串和 int 相同(类型错误:无法将 'int' 对象隐式转换为 str
)。因此,不要添加,而是将 number
作为 print
的单独参数,它会自动转换为字符串并用空格分隔。
print("The number was", number)
此外,当您可以使用标准库中的random
模块时,Numpy 在这里就显得有些过分了。令人困惑的是,np.random.randint
似乎相当于 random.randrange
,而不是 random.randint
。
import random
number = random.randrange(1, 10)
关于python - numpy 中的变量赋值不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59108640/