【问题标题】:Random words generate using python使用python生成随机词
【发布时间】:2016-09-26 11:32:46
【问题描述】:

我有一个单词列表

count=100    
list = ['apple','orange','mango']

对于上面使用随机函数的计数,是否可以选择 40% 的时间苹果、30% 的时间橙色和 30% 的时间芒果?

例如:

for the count=100, 40 times apple, 30 times orange and 30 times mango.

这个选择必须随机发生

【问题讨论】:

    标签: python-2.7 random


    【解决方案1】:

    根据对generating discrete random variables with specified weights 问题的回答,您可以使用numpy.random.choice 获得比random.choice 快​​20 倍的代码:

    from numpy.random import choice
    
    sample = choice(['apple','orange','mango'], p=[0.4, 0.3, 0.3], size=1000000)
    
    from collections import Counter
    print(Counter(sample))
    

    输出:

    Counter({'apple': 399778, 'orange': 300317, 'mango': 299905})
    

    更不用说实际上比“按要求的比例建立一个列表,然后打乱它”更容易。

    另外,shuffle 总是会产生恰好 40% 的苹果、30% 的橙子和 30% 的芒果,这与说“根据离散概率分布产生一百万个水果的样本”不同.后者是choice 解决方案所做的(以及bisect 也是)。如上可见,使用numpy时有 40%的苹果等。

    【讨论】:

      【解决方案2】:

      最简单的方法是按照需要的比例建立一个列表,然后随机排列。

      >>> import random
      >>> result = ['apple'] * 40 + ['orange'] * 30 + ['mango'] * 30
      >>> random.shuffle(result)
      

      修改计数为 1,000,000 的新要求:

      >>> count = 1000000
      >>> pool = ['apple'] * 4 + ['orange'] * 3 + ['mango'] * 3
      >>> for i in xrange(count):
              print random.choice(pool)
      

      一个较慢但更通用的替代方法是bisect a cumulative probability distribution

      >>> import bisect
      >>> choices = ['apple', 'orange', 'mango']
      >>> cum_prob_dist = [0.4, 0.7]
      >>> for i in xrange(count):
              print choices[bisect.bisect(cum_prob_dist, random.random())]
      

      【讨论】:

      • 但是如果 count=1000000 那么列表大小会向右增加,实际上我正在尝试在一个月内模拟一个每天 1000000 行的数据集,如果我这样做会更好使用相同的逻辑?
      • 这个概念非常笼统,有很多方法可以建立在它之上。我编辑了答案以显示如何使用 random.choice() 从元素比例适当的池中一次选择一个。您也可以进行累积分布并使用 bisect 进行选择,但这对于您描述问题的方式来说太过分了。
      猜你喜欢
      • 1970-01-01
      • 2013-09-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多