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循环中生成的每个位置都是唯一的,并且没有重复项?
答案 0 :(得分: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)
答案 1 :(得分:0)