【问题标题】:Select sublist where each element has a 1.5% chance to be included选择每个元素有 1.5% 的机会被包含的子列表
【发布时间】:2018-02-21 01:43:11
【问题描述】:
     tmp = []
     while len(tmp) == 0:
         for i in range(0,385):
             # Multiplying by 100 in order to remove the decimal point
             if randint(0,10000) < chance*100:
                 tmp.append(i)
     return tmp

这是我目前用来帮助解决问题的代码。输出将是这样的。

[34, 234, 243, 321]

我目前的解决方案效率很低。我试过这个:

sample(range(0,385), math.ceil(chance*3.85))

但它不会产生相同的效果。另外,如果你能告诉我这叫什么名字,那就太好了。

【问题讨论】:

    标签: python arrays numpy random sublist


    【解决方案1】:
    import numpy as np
    
    n = 385
    chance = 0.015  # Chance of 1.5%
    main_list = np.arange(n)  # Generate initial list
    rnd = np.random.uniform(size=main_list.shape)  # Generate random number between 0 and 1
    
    sublist = main_list[rnd < chance]  # Select numbers
    

    【讨论】:

    • 太棒了,这正是我想要的!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-04-19
    • 2022-08-19
    • 2012-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-09
    相关资源
    最近更新 更多