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

2024-05-26 11:54:13 发布

您现在位置: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)

但它不起作用,我想知道我如何才能从名单上永久删除该项目,以便在15轮比赛中被删除。在


Tags: and代码import程序id游戏soon
2条回答

当前,在循环的每次迭代中重新创建列表。您需要在循环之前创建列表。同时:

  • 喜欢用range(python3中的迭代器)而不是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)

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

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))

这给了

^{pr2}$

相关问题 更多 >