在python中划分两个列表 [英] Divide two lists in python

查看:90
本文介绍了在python中划分两个列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个列表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]

是否可以像上面的变量c一样在Python中获得它们的比率?我尝试输入:

Is it possible to obtain their ratio in Python, like in variable c above? I tried to type:

 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]

或者在numpy中,您可以执行a/b

Or in numpy you can do 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       ])

这篇关于在python中划分两个列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆