2016-12-10 125 views
1

我隨機抽取兩個元創建一個元組列表,像這樣:如何從列表中隨機選擇一個元組?

tuple1 = ('green','yellow','blue','orange','indigo','violet') 
tuple2 = ('tree',2,'horse',4,6,1,'banana') 

mylist = [(t1,t2) for item1 in tuple1 for item2 in tuple2] 

這當然給了我這樣的:

[('green','tree'),('yellow', 2)]等。

但是然後,我想隨機從生成的mylist中選擇一個兩項目元組。換句話說,返回類似('green',2)

如何從列表中隨機選擇一個兩項目元組?我嘗試以下,但它不工作:

my_single_tuple = random.choice(mylist.pop()) 

我會爲任何線索或建議表示感謝。

[編輯]我不清楚目標:我想刪除(彈出)從列表中隨機選擇的元組。

+0

執行上述代碼的結果:'NameError:name't1'未定義' – RomanPerekhrest

+3

'random.choice'需要一個列表,爲什麼不只是'my_single_tuple = random.choice(mylist)'? – rodrigo

+0

這應該可能是'mylist = [(item1,item2)for item1 in tuple1 for item2 in tuple2]' –

回答

2

如果你想選擇一個元組,然後刪除它只是獲得索引,然後將其刪除。

import random 

tuple1 = ('green','yellow','blue','orange','indigo','violet') 
tuple2 = ('tree',2,'horse',4,6,1,'banana') 

mylist = [(item1,item2) for item1 in tuple1 for item2 in tuple2] 


while len(mylist) > 0: 
    index = random.randint(0,len(mylist)-1) 
    print(mylist[index]) 
    del mylist[index] 
+2

我說,*「這就是爲什麼字面上有一個'random.randrange'」*。我不確定最後的改變是否有助於解決問題,是否存在'list.pop'問題?一些跡象表明,OP想要完全清除列表並只打印其中的元素? – jonrsharpe

+1

爲什麼不使用random.shuffle *一次*然後從最後流行元素? –

2

如果你需要這個多次做,只是洗牌的名單一次,然後從前面彈出項目:

random.shuffle(mylist) 
mylist.pop() 
mylist.pop() 

+0

僅當列表的原始順序無用時纔有效。 – jonrsharpe

+0

是的,我正在考慮從列表中彈出隨機項目直到列表爲空或滿足某些條件的場景。 – RemcoGerlich

1

我想我找到問題的答案:

my_item = mylist.pop(random.randrange(len(mylist))) 

這成功地給了我一個隨機元組從列表中。謝謝@ philipp-braun,你的回答非常接近,但對我來說不起作用。

相關問題