简体   繁体   English

如何通过Python中另一个列表的相应成员划分列表成员?

[英]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. 奖励:结果是一个整数列表[0,0,1,0,1,0 [0, 0, 1, 0, 1, 0] ,而不是浮点列表。 What's the easiest way to get a list of floats? 获取浮动列表的最简单方法是什么?

Use zip: 使用zip:

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

The most elegant way to get floats is to upgrade to Python 3.x. 获得浮动的最优雅方法是升级到Python 3.x.

If you need to use Python 2.x then you could write this: 如果你需要使用Python 2.x那么你可以这样写:

>>> [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 / . 但请注意,这会影响程序中各处的划分行为,因此您需要仔细检查是否有任何需要整数除法的地方,如果是,请写//而不是/

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)]

不使用zip和float:

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

If you happen to be using numpy , you can use the following ideas: 如果你碰巧使用numpy ,你可以使用以下想法:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM