我有2个列表a
和b
:
a = [3, 6, 8, 65, 3]
b = [34, 2, 5, 3, 5]
c gets [3/34, 6/2, 8/5, 65/3, 3/5]
是否有可能在Python中获得它们的比例,就像上面的变量c
一样?我试着输入:
a/b
我收到错误:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for /: 'list' and 'list'
答案 0 :(得分:29)
>>> from __future__ import division # floating point division in Py2x
>>> a=[3,6,8,65,3]
>>> b=[34,2,5,3,5]
>>> [x/y for x, y in zip(a, b)]
[0.08823529411764706, 3.0, 1.6, 21.666666666666668, 0.6]
或numpy
您可以a/b
>>> import numpy as np
>>> a=np.array([3,6,8,65,3], dtype=np.float)
>>> b=np.array([34,2,5,3,5], dtype=np.float)
>>> a/b
array([ 0.08823529, 3. , 1.6 , 21.66666667, 0.6 ])
答案 1 :(得分:17)
内置的map()功能可以解决这些问题:
>>> from operator import truediv
>>> a=[3,6,8,65,3]
>>> b=[34,2,5,3,5]
>>> map(truediv, a, b)
[0.08823529411764706, 3.0, 1.6, 21.666666666666668, 0.6]
答案 2 :(得分:10)
使用zip
和列表理解:
>>> a = [3,6,8,65,3]
>>> b = [34,2,5,3,5]
>>> [(x*1.0)/y for x, y in zip(a, b)]
[0.08823529411764706, 3.0, 1.6, 21.666666666666668, 0.6]
答案 3 :(得分:9)
你可以使用list comprehension(逐个元素)来完成这个:
div = [ai/bi for ai,bi in zip(a,b)]
注意,如果你想要浮点除法,你需要指定它(或使原始值浮动):
fdiv = [float(ai)/bi for ai,bi in zip(a,b)]
答案 4 :(得分:1)
使用numpy.divide
c=np.divide(a,b)
答案 5 :(得分:0)
您可以使用以下代码:
a = [3, 6, 8, 65, 3]
b = [34, 2, 5, 3, 5]
c = [float(x)/y for x,y in zip(a,b)]
print(c)