如何在Python中调试“TypeError:不支持的操作数类型”?

2024-06-09 10:52:37 发布

您现在位置:Python中文网/ 问答频道 /正文

sentence = "ask not what your country can do for you".upper()

uniquewords = sentence.split(' ')
wordlist = []
positionlist = []

for i in uniquewords:
    if i not in wordlist:
        wordlist.append(uniquewords)
    positionlist.append(str(wordlist.index(uniquewords)+1))

joinlist = " ".join(list[i-1] for i in positionlist)

joinlist变量处有错误,这是语法错误:

Traceback (most recent call last):
  File "temp.py", line 12, in <module>
    joinlist = " ".join(list[i-1] for i in positionlist)
  File "temp.py", line 12, in <genexpr>
    joinlist = " ".join(list[i-1] for i in positionlist)
TypeError: unsupported operand type(s) for -: 'str' and 'int'

我无法让我的代码工作,即使我已尝试解决问题多次。你知道吗


Tags: inpyfornottempsentencelistfile
1条回答
网友
1楼 · 发布于 2024-06-09 10:52:37

您的错误在这行:

joinlist = " ".join(list[i-1] for i in positionlist)

错误显示:

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

i的值是一个字符串(它的类型是str),您正在减去1。例如,在交互式提示中:

>>> '1' - 1
Traceback (most recent call last):
TypeError: unsupported operand type(s) for -: 'str' and 'int'

i不应该是一个字符串,但您可以使用以下行:

positionlist.append(str(wordlist.index(uniquewords)+1))

改为:

positionlist.append(wordlist.index(uniquewords)+1)

你应该看到下一个错误(c:

TypeError: 'type' object is not subscriptable

从这个表达式:

list[i-1]

list意味着什么?那是你自己解决和回答的问题。你知道吗

相关问题 更多 >