首页 > 解决方案 > Python List 无法将变量识别为整数

问题描述

该代码适用于使用 Randint 和列表的井字游戏。有人可以解释为什么会出现错误吗?我试图将其更改为整数和字符串,但它仍然不起作用。

import random 

boardt = [1, 2, 3]
boardm = [4, 5, 6]
boardd = [7, 8, 9]
print ("This is Tic Tac Toe / Noaughts and Crosses")
print ('(x)Human against (o) "machine"')
print (boardt)
print (boardm)
print (boardd)
hpos = int(input("Pick a position "))
if hpos == 1:
    boardt.remove(1)
    boardt.insert(0,"X")
    mpos = (int(random.randint(1,8)))
    if mpos == 1 or 2:
        boardt.remove(mpos)
        boardt.insert(mpos,"O")

    elif mpos == 3 or 4 or 5:
        boardm.remove(mpos)
        boardm.insert(mpos,"O")

    elif mpos == 6 or 7 or 8:
        boardd.remove(mpos)
        boardd.insert(mpos,"O")

错误:

Traceback (most recent call last):
  File "main.py", line 16, in <module>
    boardt.remove(mpos)
ValueError: list.remove(x): x not in list

标签: python

解决方案


主要问题是 egif mpos == 1 or 2不测试值是 1 还是 2。
测试应该是if mpos == 1 or mpos == 2:,或者更好:if mpos in (1, 2):


推荐阅读