从列表中删除项目并将其更新为python

时间:2014-11-28 15:46:20

标签: python list

我有一个游戏,玩家从列表中选择挑战:

locallist = ['Ann-Marie, the butcher (1)', 'Bella, the flourist (2)', 'Caitlyn, the painter(3)', 'Daniel, the scientist (4)', 'Lauren, the Zookeeper (5)']
在每次挑战之后,我重新打印列表,以便他们可以挑选另一个挑战,我正在寻找它以打印一个列表,不包括他们刚才所做的人员挑战。

感谢您的任何见解

2 个答案:

答案 0 :(得分:3)

您可以根据用户的选择使用删除或弹出:

locallist = ['Ann-Marie, the butcher (1)', 'Bella, the flourist (2)', 'Caitlyn, the painter(3)', 'Daniel, the scientist (4)', 'Lauren, the Zookeeper (5)']

pick = 'Ann-Marie, the butcher (1)'
locallist.remove('Ann-Marie, the butcher (1)')
print(locallist)

pick = 1
locallist.pop(1)
print(locallist)

['Bella, the flourist (2)', 'Caitlyn, the painter(3)', 'Daniel, the scientist (4)', 'Lauren, the Zookeeper (5)']
['Bella, the flourist (2)', 'Daniel, the scientist (4)', 'Lauren, the Zookeeper (5)']

如果您想保持原始列表不变,请复制locallist

remaining = locallist[:]
pick = 'Ann-Marie, the butcher (1)'
remaining.remove('Ann-Marie, the butcher (1)')
print(remaining)

pick = 1
remaining.pop(1)
print(remaining )

['Bella, the flourist (2)', 'Caitlyn, the painter(3)', 'Daniel, the scientist (4)', 'Lauren, the Zookeeper (5)']
['Bella, the flourist (2)', 'Daniel, the scientist (4)', 'Lauren, the Zookeeper (5)']

使用pop也会为您提供值,以便您可以根据需要使用它:

pick = 1
challenge = remaining.pop(1)
print("You chose the following challenge: {}".format(challenge))
You chose the following challenge: Bella, the flourist (2)

答案 1 :(得分:0)

您可以从原始列表创建集合。然后从集和打印集中删除拾取的项目。