2016-05-22 17 views
0
import random 

def generate_broadcast_nodes(): 
    node_locations = [] 

    locations = ["barracks","bathroom","bridge","cq","dininghall","dropship","fighterbay","logi","reactor","shiphangar"] 

    for i in range(3): 
     node_locations.append(locations.pop(random.randint(0,len(locations)-1))) 
    return node_locations 

如何確保在此for循環中生成的每個位置都是唯一的並且沒有重複項?我如何保證隨機生成的數據在Python中是唯一的?

+2

'return list(set(node_locations))''確保沒有重複 –

+2

你不是已經這麼做嗎? 'locations'具有完全獨特的條目,你彈出每個條目意味着你不能再次獲取它。 – Dair

+0

@ cricket_007但是這可能導致選擇的元素數量比預期的要少 –

回答

0

您可以使用一個set,它的定義或者有或沒有。但是,只要原始位置列表不包含重複項,您的代碼將始終具有唯一的位置。這是因爲你是poppinglocations返回元素(並具有從列表中刪除它的副作用)

+0

我不太喜歡'set'解決方案,因爲它必須包含在一個理論上無限的非確定性循環中。在池中有很多重複的情況下,這也是低效的。 –

2

由於locations.pop(random.randint(0,len(locations)-1))不僅返回元素也來自node_locations中刪除元素的功能已經保證了在node_locations中沒有重複,只要locations不包含任何內容。

但是,生成隨機樣本的更好方法是使用random.sample()

import random 

def generate_broadcast_nodes(): 
    locations = ["barracks", "bathroom", "bridge", "cq", "dininghall", 
       "dropship", "fighterbay", "logi", "reactor", "shiphangar"] 

    return random.sample(locations, 3) 
+0

可能值得注意的是,在包含重複項的情況下,該列表可以轉換爲一個集合。 –

+0

當然,但在這種情況下,可能的選項列表是硬編碼的,不應該是必需的。 –

相關問題