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?
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.
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.
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?
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 int
s to be float
, or from __future__ import division
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