Python - 列表中的索引错误
我正在写程序,需要输入2个第一个方向&第二个是在一行中的步骤,我通过使用split('')这样做所有这些输入需要在while循环 但用户不想进入更多的投入,他刚刚进入空行和终止,但它是不会发生不知道为什么......这是我的代码Python - 列表中的索引错误
while True:
movement = input().split(' ')
direction = movement[0].lower()
step = int(movement[1])
if movement != '' or movement != 0:
if direction == 'up' or direction == 'down':
if y == 0:
if direction == 'down':
y -= step
else:
y += step
else:
if direction == 'down':
y -= step
else:
y += step
elif direction == 'left' or direction == 'right':
if x == 0:
if direction == 'right':
x -= step
else:
x += step
else:
if direction == 'right':
x -= step
else:
x += step
else:
current = (x, y)
print(original)
print(current)
break
但我输入银行输入它显示了这个消息
Traceback (most recent call last):
File "C:/Users/Zohaib/PycharmProjects/Python Assignments/Question_14.py",
line 04, in <module>
step = int(movement[1])
IndexError: list index out of range
你可以做你的清单len(),如果你没有得到任何mo vement你做任何的逻辑,例如
if len(movement) == 0:
# Your logic when you don't have any input
pass
else:
# Your logic when you have at least one input
pass
不适用于这种情况。 ''print(len(“”。split('')))''是''1''(因为列表有1个元素 - 一个空字符串)! –
我使用这个条件len(movement)== 1:break –
移动你的方向=移动[0] .lower()进线if语句,这将让他们只运行,如果运动!=“”,你需要改变你的if语句,否则它永远是真的,因为移动不能同时为''和0
另外,将分割移入if语句中,以便在if语句中进行比较时,只是比较运动。 (”” .split()返回[])
while True:
movement = input()
if movement != '' and movement != '0':
movement = movement.split()
direction = movement[0].lower()
step = int(movement[1])
del movement[1]
if direction == 'up' or direction == 'down':
if y == 0:
if direction == 'down':
y -= step
else:
y += step
else:
if direction == 'down':
y -= step
else:
y += step
elif direction == 'left' or direction == 'right':
if x == 0:
if direction == 'right':
x -= step
else:
x += step
else:
if direction == 'right':
x -= step
else:
x += step
else:
current = (x, y)
print(original)
print(current)
break
*,但用户不希望进入更多的投入,他刚刚进入空行和终止*。那么当你尝试在空行上使用'movement.split()'时,你会怎么想呢?在结果列表中将创建多少个元素? –
sidetrack有点,但为什么你需要添加一个if x == 0语句,因为要执行的代码在if和else中都是相同的(对于y也是一样的) – chngzm
我想当用户没有更多条目时他只需输入空白行并循环终止 –