这段代码运行后,为什么报错信息说num是一个空列表?
代码x = input('请输入字符串:')
x = x.split()
num = []
for each in x :
if each =='[' or each =='{' or each =='(':
num = num.append(each)
else:
y = num.pop()
if each ==']' and y == '[' or each == '}' and y == '{' or each == '(' and y ==')':
print('合法')
else:
print('非法')
运行结果
Traceback (most recent call last):
File "C:\Users\xy_xuan\Desktop\1.py", line 8, in <module>
y = num.pop()
IndexError: pop from empty list 问题出在这一行代码上:num = num.append(each)。
在这行代码中,你试图将元素each添加到空列表num中,并将结果赋值给num。然而,列表的append方法没有返回值,它会直接在原列表上进行修改。所以,当你执行num = num.append(each)时,实际上num被赋值为None。
因此,在后续的代码中,当你尝试使用num.pop()时,由于num是一个空列表(None),所以会报错"IndexError: pop from empty list"。
要解决这个问题,你只需要将这一行代码修改为:num.append(each)。这样,元素each将会被添加到num列表中,而不会改变num的值。修改后的代码如下:
x = input('请输入字符串:')
x = x.split()
num = []
for each in x:
if each == '[' or each == '{' or each == '(':
num.append(each)
else:
y = num.pop()
if each == ']' and y == '[' or each == '}' and y == '{' or each == '(' and y == ')':
print('合法')
else:
print('非法')
这样修改后,代码就能正常运行了。 isdkz 发表于 2023-8-30 17:25
问题出在这一行代码上:num = num.append(each)。
在这行代码中,你试图将元素each添加到空列表num中, ...
修改了以后报错是一样的 没看懂你想要写什么程序
如果你输入了abcd
那么第一次进入到for循环的时候
each = a
再经过if判断,a不符合,所以进入到else,然后y是num数组的元素,但是你只有进入到第一个if才可能像数组里添加元素,所以现在数组是空的
or each in x :
if each =='[' or each =='{' or each =='(':
num = num.append(each)
else:
if (len(num)>=1):
y = num.pop()
if each ==']' and y == '[' or each == '}' and y == '{' or each == '(' and y ==')':
print('合法')
else:
print('非法')
页:
[1]