永久删除Python中列表中的元素?

时间:2014-05-04 18:05:13

标签: python

我有这个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轮中删除它。

2 个答案:

答案 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