当我尝试使用输入的变量来确定列表中的某个字符串时,我正在浏览一些代码。我已经使用了很多输入分隔来将它变成2个字符串,我看不出我的代码有什么问题。
我试图在我的主项目中使用一段代码,但它出现了故障。
我已经尝试在我的主项目中使用此代码:
equipped = []
bag = ['foo', 'bar']
act = input()
if "Equip" or "equip" in act:
inputPieces = act.split(' ')
base = inputPieces[0]
argument = inputPieces[1]
slotnumber = int(argument) - 1
item_equip = bag[slotnumber]
equipped.append(item_equip)
当我尝试输入时,equip 1
它应该将“foo”添加到装备中,但它发送了一条错误消息,指出
argument = inputPieces[1]
IndexError: list index out of range
预计将采用我输入的第二部分 (1) 并将相应的字符串从“bag”附加到“equipped”。但是当我尝试这样做时,错误消息说(我认为)这部分不存在,所以它不能使用索引。
您已经使用 space(act.split(' ')) 分割数据,该空间构成一个列表。如果用户输入有用户输入空间,则列表包含多个数据。如果用户输入仅包含一个没有空格的单词,例如“equipefgfgh”,则 inputPieces[1] 将不存在。在这种情况下,您将收到问题中所述的错误。所以你必须在访问前检查:
if len(inputPieces) >1
或者您可以使用尝试/除外:
equipped = []
bag = ['foo', 'bar']
act = input()
if "Equip" in act or "equip" in act:
try:
inputPieces = act.split(' ')
base = inputPieces[0]
argument = inputPieces[1]
slotnumber = int(argument) - 1
item_equip = bag[slotnumber]
equipped.append(item_equip)
except:
print("error occured")
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句