35

我有两个列表ab

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'
4

6 回答 6

44
>>> 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       ])
于 2013-05-07T11:59:49.043 回答
21

内置的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]
于 2013-05-07T12:12:01.137 回答
13

您可以使用列表推导(逐个元素)来做到这一点:

div = [ai/bi for ai,bi in zip(a,b)]

请注意,如果要浮点除法,则需要指定此值(或使原始值浮动):

fdiv = [float(ai)/bi for ai,bi in zip(a,b)]
于 2013-05-07T11:59:46.880 回答
9

使用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]
于 2013-05-07T12:00:01.197 回答
1

使用numpy.divide

c=np.divide(a,b)
于 2020-09-18T18:05:13.743 回答
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)
于 2019-02-26T17:04:50.110 回答