Question

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?

Was it helpful?

Solution

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?

OTHER TIPS

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

List iteration and map function gets you there very quickly.

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

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

>>> monkey = [ float(m.strip()) for m in monkey]

>>> banana = [ float(m.strip()) for m in banana]

>>> def div(a,b):

...     return a/b

... 

>>> map(div, banana, monkey)

[9.0, 4.0, 12.0]

>>> 

A list comprehension, like [an_expression for some_variable in some_sequence] returns you a new list. Your example just drops these results.

# remove trailing whitespace and convert strings to numbers
monkey_numbers = [int(item.strip()) for item in monkey]
banana_numbers = [int(item.strip()) for item in banana]

# a traditional loop
bananasplit = [] # an empty list
for i in range(len(banana_numbers)):
  # make bananasplit longer on each iteration
  bananasplit.append(banana_numbers[i] / monkey_numbers[i])

Then, you can use a list comprehension instead of a loop since your expression is so simple. You will need zip function that takes two lists and makes a list of pairs.

# divide in one statement
bananasplit = [
  banana_portion / monkey_bunch 
  for (banana_portion, monkey_bunch) in 
  zip(banana_numbers, monkey_numbers)
]

Of course, you are free to use shorter identifiers; I used long names to make their roles easier to understand.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top