2015-12-02 179 views
0

我有一個列表,我試圖從列表中獲取隨機項並將它們放入一個變量的Python腳本,但我注意到,當我運行該程序幾次(約20次左右),最終它將打印出2個像「蘋果蘋果」一樣的物品。如何在使用random.choice()後從列表中刪除一個項目?

import random 

list = ['apples','grapes','bannas','peaches','pears','oranges','mangos'] 
a = random.choice(list) 
b = random.choice(list) 
while a in (list[0],list[1],list[2],list[3],list[4],list[5],list[6]): 
    a = random.choice(list) 

while b in (list[0],list[1],list[2],list[3],list[4],list[5],list[6]): 
    b = random.choice(list) 

print(a + ' ' + b) 

while循環應該使變量每次都包含一個唯一值,但它不會。

+0

如果您打算最終選擇全部,甚至只是大多數列表中的項目,將它洗和流行物品關底。 –

回答

2

while a in (list[0],list[1],list[2],list[3],list[4],list[5],list[6]):相當於while a in list:。由於a只包含列表中的值,因此條件始終爲真,並且循環永遠不會結束,並且您將永遠不會達到您的打印語句。

要從一個集合中選擇多個唯一的隨機項目,請使用sample而不是choice。上述

>>> list = ['apples','grapes','bannas','peaches','pears','oranges','mangos'] 
>>> a,b = random.sample(list, 2) 
>>> a 
'bannas' 
>>> b 
'grapes' 
2

Kevins sample比較好,但我認爲這是你試圖用choice做:

import random 

fruit = ['apples', 'grapes', 'bannas', 'peaches', 'pears', 'oranges', 'mangos'] 
a_fruit = random.choice(fruit) 
b_fruit = random.choice(fruit) 

while a_fruit == b_fruit: 
    b_fruit = random.choice(fruit) 

print("{} - {}".format(a_fruit, b_fruit)) 

一個幾句話:

  • list是蟒蛇的build in function。永遠不要命名列表(或字典或刪除等)
  • 正如凱文提到while循環是無用的,並且將永遠運行,因爲它應該總是評估爲真。
+0

感謝列表上的建議,我將在未來記住這一點。 –

+0

在凱文的答案random.sample()似乎使while循環多餘,但你是正確的,這正是我試圖用while循環完成。 –

0

另一種選擇:如果你不關心名單,我會使用pop,如果你這樣做,那麼你可以進行復制,然後使用pop(我fon't知道要如何使用您的列表)。

idx = random.randint(0,len(fruit_list)) 
a = fruit_list.pop(idx) 

idx = random.randint(0,len(fruit_list)) 
b = fruit_list.pop(idx) 

print(a + ' ' + b) 

另一種方法是將您的列表打亂/洗牌,然後按順序逐個拿起項目。

random.shuffle(fruit_list) 
a = fruit_list[0] 
b = fruit_list[1] 

print(a + ' ' + b) 
使用流行的

,再次:

random.shuffle(fruit_list) 
a = fruit_list.pop() 
b = fruit_list.pop() 

print(a + ' ' + b) 
相關問題