Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to combine elements from two lists into a third?

Tags:

python

list

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' 
like image 481
ely Avatar asked May 07 '13 11:05

ely


People also ask

How do you combine list elements in python?

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.

How do I combine two lists of elements?

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.

How do you concatenate 3 lists?

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?


2 Answers

>>> 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       ]) 
like image 120
jamylak Avatar answered Sep 23 '22 13:09

jamylak


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] 
like image 30
Raymond Hettinger Avatar answered Sep 23 '22 13:09

Raymond Hettinger