I have two lists a
and 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?
I tried a/b
and got the error:
Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unsupported operand type(s) for /: 'list' and 'list'
Note: The join() method provides a flexible way to create strings from iterable objects. It joins each element of an iterable (such as list, string, and tuple) by a string separator (the string on which the join() method is called) and returns the concatenated string.
Join / Merge two lists in python using + operator In python, we can use the + operator to merge the contents of two lists into a new list. For example, We can use + operator to merge two lists i.e. It returned a new concatenated lists, which contains the contents of both list_1 and list_2.
You can concatenate multiple lists into one list by using the * operator. For Example, [*list1, *list2] – concatenates the items in list1 and list2 and creates a new resultant list object. Usecase: You can use this method when you want to concatenate multiple lists into a single list in one shot. What is this?
>>> 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
>>> 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 ])
The built-in map() function makes short work of these kinds of problems:
>>> 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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With