2017-05-29 38 views
0

我正在尋找一些Python代碼的幫助,我一直在爲有趣而寫作,因此麻煩的一段代碼是:使用變量來確定要打印的集合中的哪個值

v = randint(1,7) 
if v != 7: 
    d = randint(1,5) 
    if d == 1: 
     print(vdset[v], file=text_file) 

我的目標是使用randint從我的集合中選擇一個隨機值,但是,在運行時我得到的錯誤是'set' object does not support indexing。那麼我想我需要用set來代替我的用法,但我不確定哪些方法可行。

+0

集合沒有排序,所以它們不能被索引。您可以改用列表。 –

+0

順便從一個序列中挑選一個隨機元素最好使用'random.choice()'完成。然而,你仍然需要一個列表或元組。 –

+0

你可以'列出(vdset)[v]'如果你真的結婚了'vdset'' –

回答

0

問題是一個集合是唯一元素的無序集合。你應該在data structure看看的Python:

你可以試試:

v = randint(1,7) 
    if v != 7: 
     d = randint(1,5) 
     if d == 1: 
      print(list(vdset)[v], file=text_file) 
0

你也可以使用random.choice。這在集合不支持索引的情況下也存在同樣的問題,但您可以簡單地將集合轉換爲列表(支持索引)。

>>> from random import choice 
>>> my_set = {1, 3, 2, 7, 5, 4} 
>>> choice(my_set) 
Traceback (most recent call last): 
... 
TypeError: 'set' object does not support indexing 
>>> choice(list(my_set)) 
3 
相關問題