首页 > 解决方案 > while 循环中出现不支持的操作数类型错误

问题描述

我正在使用两个主要的 while 循环。一种用于输入。其他用于运行测试。

我收到了这个错误:

Error : File "n1.py", line 22, in <module>    while j<n-1 and line[a][j+1]-line[a][j]<=2: TypeError: unsupported operand type(s) for -: 'list' and 'int'

当这一行中的所有内容都是整数类型时,为什么我会收到错误消息。

我附上了我的编辑器的截图。

标签: error-handling

解决方案


一切都不是整数。在第 3 行你有n=[](这是一个list)然后在第 21 行你有n-1

您不能在intlist之间使用减法

这导致:

TypeError: unsupported operand type(s) for -: 'list' and 'int'

也许您想访问列表中的最后一项

n[-1] # Make sure there is at least one item otherwise it throws an IndexError

或者,也许您想获取列表的最后一个索引

len(n) - 1

推荐阅读