我有一个代码(游戏的一部分我正在尝试做),它检查一个列表的元素和另一个列表的元素…基本上,它做的是比较每个元素的每个索引,如果2个索引相等,它会将它从列表中删除
代码如下:
checkctr = 0
x = 0
while checkctr < 4:
if p1guesslist[x] == hidden[x]:
black += 1
p1nonhidden.remove(hidden[x]) #p1nonhidden is a copy of hidden
p1nonmatch.remove(hidden[x]) #p1nonmatch is a copy of p1guesslist
x += 1
checkctr += 1
for p1guess in p1nonmatch: #p1guess is a 4 digit user input
if p1guess in p1nonhidden:
white += 1
代码如何在输出中工作的示例:
hidden = [1, 1, 2, 3] #elements of this is randomly generated
p1guesslist = [1, 3, 2, 4] #elements of this list is from p1guess
black = 2 #initial value is 0
white = 1 #initial value is 0
如果两个列表的索引相等,black将获得+1并从列表中删除。然后检查其余元素是否在隐藏列表中,如果在-white+1中
问题是,程序应该要求用户输入,直到达到一定数量的数字,因此p1guesslist会在每次输入时更改元素。发生的情况是:
hidden = [1, 1, 2, 3]
p1guesslist = [1, 3, 2, 4] #first input
black = 2
white = 1
p1guesslist = [1, 1, 2, 3] #second input
ValueError: list.remove(x): x not in list
我知道因为列表.删除()发生ValueError。。。你知道吗
所以我在想,是否有一种方法可以在检查完成后将从隐藏中移除的元素恢复到隐藏中,以避免错误
*我在这个在线记事本中放了一个小版本的游戏,以防你想看它http://shrib.com/UMYKxGiY我用python3.4.1做了这个
处理异常:
是的。不再有“x不在列表中”
相关问题 更多 >
编程相关推荐