2017-10-15 46 views
-1

我需要在2个变量中生成10个随机数并计算它们之间的比率。 我的代码如下。我究竟做错了什么?不支持的操作数类型为/:'list'和'list'Python

from random import randint 
N=10 
a = [random.randint(0, 10) for _ in range(N)] 
b = [random.randint(0, 10) for _ in range(N)] 
print (a,b) 
ratio = a/b 

TypeError: unsupported operand type(s) for /: 'list' and 'list' 
+1

诊断似乎很清楚。 '/'运算符不接受类型列表的操作数。你想计算list * elements *对的商数,而不是列表本身的商数。 –

回答

0

列表默认情况下不支持算术运算符,因为元素可能不支持算术事情(他们甚至可能不是数字,他们可能是混合型的!)。

你会想去做

from random import randint 

N = 10 
a = [random.randint(0, 10) for _ in range(N)] 
b = [random.randint(0, 10) for _ in range(N)] 
ratio = [ai/bi for ai, bi in zip(a, b)] 

print(a, b) 
print(ratio) 

东西更方便的方式做这些类型的计算,看看NumPy

+0

谢谢我是全新的,我也会研究NumPy。 –

相关问题