在Python中从列表中永久删除元素?

在Python中从列表中永久删除元素?,python,Python,我有一个Python程序来玩“名人ID”游戏,在我的游戏中,我有15轮 守则: while round<15 import random celeblist=["a","b","c","d","e","f"] ##and so on celebchoice=random.choice(celeblist) celeblist.remove(celebchoice) 当前,在循环的每个迭代中重新创建列表。您需要在循环之

我有一个Python程序来玩“名人ID”游戏,在我的游戏中,我有15轮

守则:

while round<15
         import random
         celeblist=["a","b","c","d","e","f"] ##and so on
         celebchoice=random.choice(celeblist)
         celeblist.remove(celebchoice)

当前,在循环的每个迭代中重新创建列表。您需要在循环之前创建列表。此外:

  • 更喜欢使用
    范围(Python3中的迭代器)而不是
    while
  • 在开始时导入
    随机
    ,而不是在循环中导入
代码已更正:

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)

为什么不预选你的随机名人,每轮一个

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

while
循环之前创建列表。可能重复