2014-01-14 83 views
1

我想在Python中創建一個小程序,它從列表中選取一個隨機字符串並打印字符串。但是程序通常會選擇相同的字符串兩次。Python只輸出一次隨機/選擇一個字符串

有沒有辦法確保每個字符串只輸出一次?

我迄今爲止代碼:

from random import choice 
food = ['apple', 'banana', 'strawberry', 'blueberry', 'orange'] 
print 'You should eat today :' + choice(food) 
print 'You should eat tomorrow :' + choice(food) 
+0

嘗試類似 - 在食品foodItem:打印foodItem – acutesoftware

回答

3
today = choice(food) 
tomorrow = today 
while tomorrow == today: 
    tomorrow = choice(food) 
print 'You should eat today : {}'.format(today) 
print 'You should eat tomorrow : {}'.format(tomorrow) 
5

如果你不關心列表的排序之後,你可以洗牌的名單,然後再遍歷它。

import random 
food = ['apple', 'banana', 'strawberry', 'blueberry', 'orange'] 
random.shuffle(food) 

for f in food: 
    print f 

如果你不需要所有這些,你應該只是彈出一個項目,當你想要它(這將耗盡列表)。

import random 
food = ['apple', 'banana', 'strawberry', 'blueberry', 'orange'] 
random.shuffle(food) 

try: 
    print food.pop() 
except IndexError: 
    print "No more food left!" 

# .... 
# some more code 
# I'm hungry! 

try: 
    print food.pop() 
except IndexError: 
    print "No more food left!" 

# etc. 

嘗試...除了需要處理的情況下,你想從一個空的列表中獲取食物。

1

我會使用random.sample

>>> from random import sample 
>>> food = ['apple', 'banana', 'strawberry', 'blueberry', 'orange'] 
>>> sample(food, 2) 
['banana', 'blueberry'] 
>>> sample(food, 2) 
['orange', 'apple'] 
>>> today, tomorrow = sample(food, 2) 
>>> today 
'banana' 
>>> tomorrow 
'blueberry' 
2

相反的choice,使用sample

today, tomorrow = random.sample(food, 2) 

從文檔:

random.sample(population, k)

返回從​​序列中選擇的唯一元素的長度列表。用於無需更換的隨機抽樣。

1

如果你不在意在銷燬過程中的列表,你可以使用這個功能,而不是選擇。

import random 

def del_choice(food): 
    if food: 
     return food.pop(random.randrange(len(food))) 
    return None 
+1

...或一次洗牌的列表,並彈出從中隨機元素,直到列表爲空。 – bgporter

+1

是的......但只有當你不是在pop調用之間以某種方式再次對列表進行排序的時候;]實際上,可能有太多的用例提供單一的解決所有答案 –