2017-04-07 61 views
7

隨機抽樣我有這樣的名單:獲取與更換

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

,我想從它那裏得到4個隨機字母,但包括重複。

運行這樣只會給我4個獨特的字母,但從來沒有任何重複的字母:

print(random.sample(colors,4)) 

如何獲得的4種顏色列表,重複的字母可能嗎?

回答

9

隨着random.choice

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

如果你需要不對應的值的列表中的數值的個數,然後用range

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

從Python 3.6 onwa您也可以使用random.choices(複數)並指定您需要的值的數量作爲k參數。

0

此代碼將生成您需要的結果。我爲每條評論添加了評論,以幫助您和其他用戶關注此過程。請隨時提出任何問題。

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

在Python 3.6,新random.choices()功能將直接解決這一問題:

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