我有这个Python程序来玩游戏Celebrity ID,在我的游戏中,我有15轮。
代码:
while round<15
import random
celeblist=["a","b","c","d","e","f"] ##and so on
celebchoice=random.choice(celeblist)
celeblist.remove(celebchoice)
但它不起作用,我想知道如何永久删除列表中的项目,以便在15轮中删除它。
答案 0 :(得分:1)
目前,您在循环的每次迭代中重新创建列表。您需要在循环之前创建列表。也:
for
(Python 3中的迭代器)而不是range
while
循环
random
而不是循环代码已更正:
import random
celeblist = ["a","b","c","d","e","f"] # and so on
for round in range(15):
celebchoice = random.choice(celeblist)
print("Current elem: %s" % celebchoice)
celeblist.remove(celebchoice)
答案 1 :(得分:0)
为什么不预先选择你的随机名人,每轮一个?
import random
celebs = [
"a", "b", "c", "d", "e", "f",
"g", "h", "i", "j", "k", "l",
"m", "n", "o", "p", "q", "r" # need at least 15
]
chosen = random.sample(celebs, 15)
for round,celeb in enumerate(chosen, 1):
print("{}: {}".format(round, celeb))
给出了
1: j
2: a
3: r
4: f
5: n
6: o
7: g
8: k
9: i
10: l
11: e
12: b
13: d
14: q
15: p