Rich Armstrong
Rich Armstrong

Reputation: 1432

How do I divide the members of a list by the corresponding members of another list in Python?

Let's say I have two data sets. I have a week-by-week tally of users who tried my service.

trials = [2,2,2,8,8,4]

And I have a week by week tally of trial users who signed up.

conversions = [1,0,2,4,8,3]

I can do it pretty quickly this way:

conversion_rate = []
for n in range(len(trials)):
   conversion_rate.append(conversions[n]/trials[n])

Can you think of a more elegant way?

Bonus: The result of this is a list of ints [0, 0, 1, 0, 1, 0] , not a list of floats. What's the easiest way to get a list of floats?

Upvotes: 5

Views: 3339

Answers (4)

dheerosaur
dheerosaur

Reputation: 15172

Without using zip and float:

[1.0*conversions[n]/trials[n] for n in xrange(len(trials))]

Upvotes: 2

yassin
yassin

Reputation: 6707

If you happen to be using numpy, you can use the following ideas:

import numpy as np
conversion_rate = np.divide(trials, conversions)

or, using broadcasting:

import numpy as np
trials = np.array([2, 2, 2, 8, 8, 4])
conversions = np.array([1, 0, 2, 4, 8, 3])
conversion_rate = 1.0 * trials / conversions

Upvotes: 1

Day
Day

Reputation: 9693

How about

trials = [2,2,2,8,8,4]
conversions = [1,0,2,4,8,3]
conversion_rate = [conversion / trials[n] for n, conversion in enumerate(conversions)]

Upvotes: 2

Mark Byers
Mark Byers

Reputation: 837996

Use zip:

[c/t for c,t in zip(conversions, trials)]

The most elegant way to get floats is to upgrade to Python 3.x.

If you need to use Python 2.x then you could write this:

>>> [float(c)/t for c,t in zip(conversions, trials)]
[0.5, 0.0, 1.0, 0.5, 1.0, 0.75]

Alternatively you could add this at the start of your file:

from __future__ import division

But note that this will affect the behaviour of division everywhere in your program, so you need to check carefully to see if there are any places where you want integer division and if so write // instead of /.

Upvotes: 15

Related Questions