【问题标题】:Get a random sample with replacement获取带替换的随机样本
【发布时间】:2017-09-03 01:27:06
【问题描述】:

我有这个清单:

colors = ["R", "G", "B", "Y"]

我想从中得到 4 个随机字母,但包括重复。

运行它只会给我 4 个独特的字母,但绝不会出现任何重复的字母:

print(random.sample(colors,4))

如何获得 4 种颜色的列表,并且可能有重复的字母?

【问题讨论】:

标签: python python-3.x random


【解决方案1】:

在 Python 3.6 中,新的 random.choices() 函数将直接解决该问题:

>>> from random import choices
>>> colors = ["R", "G", "B", "Y"]
>>> choices(colors, k=4)
['G', 'R', 'G', 'Y']

【讨论】:

    【解决方案2】:

    random.choice:

    print([random.choice(colors) for _ in colors])
    

    如果您需要的值的数量与列表中的值的数量不对应,则使用range

    print([random.choice(colors) for _ in range(7)])
    

    从 Python 3.6 开始,您还可以使用 random.choices(复数)并将所需的值的数量指定为 k 参数。

    【讨论】:

      【解决方案3】:

      试试numpy.random.choicedocumentation numpy-v1.13):

      import numpy as np
      n = 10 #size of the sample you want
      print(np.random.choice(colors,n))
      

      【讨论】:

        【解决方案4】:

        此代码将产生您需要的结果。我在每一行都添加了 cmets,以帮助您和其他用户遵循该过程。请随时提出任何问题。

        import random
        
        colours = ["R", "G", "B", "Y"]  # The list of colours to choose from
        output_Colours = []             # A empty list to append results to
        Number_Of_Letters = 4           # Allows the code to easily be updated
        
        for i in range(Number_Of_Letters):  # A loop to repeat the generation of colour
            output_Colours.append(random.sample(colours,1)) # append and generate a colour from the list
        
        print (output_Colours)
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-02-21
          • 1970-01-01
          • 1970-01-01
          • 2021-03-10
          相关资源
          最近更新 更多