在python中划分两个列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16418415/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Divide two lists in python
提问by ely
I have 2 lists aand b:
我有 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]
Is it possible to obtain their ratio in Python, like in variable cabove? I tried to type:
是否可以在 Python 中获得它们的比率,就像c上面的变量一样?我试着输入:
a/b
And I get an error:
我收到一个错误:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for /: 'list' and 'list'
回答by sapi
You can do this using list comprehension (element by element):
您可以使用列表理解(逐个元素)来执行此操作:
div = [ai/bi for ai,bi in zip(a,b)]
Note that if you want float division, you need to specify this (or make the original values floats):
请注意,如果您想要浮动除法,则需要指定此项(或使原始值浮动):
fdiv = [float(ai)/bi for ai,bi in zip(a,b)]
回答by jamylak
>>> 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]
Or in numpyyou can do a/b
或者在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 ])
回答by Ashwini Chaudhary
Use zipand a list comprehension:
使用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]
回答by Raymond Hettinger
回答by Shishir Nanoty
You can use the following code:
您可以使用以下代码:
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)

