[英]How to combine elements from two lists into a third?
I have two lists a
and b
:我有两个列表
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 c
above?是否可以在 Python 中获得它们的比率,就像上面的变量
c
一样?
I tried a/b
and got the error:我试过
a/b
并得到错误:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for /: 'list' and 'list'
>>> 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 numpy
you 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 ])
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)]
Use zip
and 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]
使用numpy.divide
c=np.divide(a,b)
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.