Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Divide one list by another list

I have two lists like this:

monkey = ['2\n', '4\n', '10\n']

banana = ['18\n', '16\n', '120\n']

What I want to do with these two list is make a third list, let's call it bananasplit.

I have to strip away ' \n', leaving only values and then make a formula which divides into:

bananasplit[0] = banana[0]/monkey[0]

bananasplit[1] = banana[1]/monkey[1] etc

I experimented with while-loop but can't get it right. Here is what I did:

bananasplit = 3*[None]

i = 0

while i <= 2:

    [int(i) for i in monkey]

    [int(i) for i in banana]

    bananasplit[i] = banana[i]/monkey[i]

    i += 1

How would you demolish this minor problem?

like image 853
RasmusJ Avatar asked Jan 21 '13 08:01

RasmusJ


People also ask

Can you divide a list by another list in Python?

To divide one list of numbers by another list: Use the zip function to get an iterable of tuples with the corresponding items. Use a list comprehension to iterate over the iterable. On each iteration, divide the values in the current tuple.

How do I assign a list of values from one list to another?

Using the extend() method The lists can be copied into a new list by using the extend() function. This appends each element of the iterable object (e.g., another list) to the end of the new list.


2 Answers

The following will do it:

>>> bananasplit = [int(b) / int(m) for b,m in zip(banana, monkey)]
>>> print(bananasplit)
[9, 4, 12]

As far as your original code goes, the main issue is that the following are effectively no-ops:

[int(i) for i in monkey]
[int(i) for i in banana]

To turn them into something useful, you would need to assign the results somewhere, e.g.:

monkey = [int(i) for i in monkey]
banana = [int(i) for i in banana]

Finally, it is worth noting that, depending on Python version, dividing one integer by another using / either truncates the result or returns a floating-point result. See In Python 2, what is the difference between '/' and '//' when used for division?

like image 144
NPE Avatar answered Oct 20 '22 05:10

NPE


Try something like this.

bananasplit = [x/y for x, y in zip(map(int, banana), map(int, monkey))]

If you want the float result (in python 2.x), you can change the ints to be float, or from __future__ import division

like image 21
DanielB Avatar answered Oct 20 '22 04:10

DanielB