首页 > 解决方案 > TypeError:一元操作数类型错误-:str,如何编辑输入

问题描述

我正在检查最后一块石头的重量问题,我想要一个输入部分,我可以在其中输入石头的重量。我试过了: '''

import heapq

stones = [input('input: ')] 

def LastStoneWeight(self, stones):
    stones = [-i for i in stones] #the error is here
    heapq.heapify(stones)

    while len(stones) > 1:
        new = heapq.heappop(stones) - heapq.heappop(stones)
        if new != 0:
        heapq.heappush(stones, new)
return -stones[0] if stones else 0

print('%s' %LastStoneWeight(stones, stones))

'''

但是发生了错误。你们能帮帮我吗?非常感谢:D

标签: pythonpython-3.xstringlistinput

解决方案


问题是您将减号 ('-') 应用于字符串类型的变量。

如果您需要一个数字,则可以将输入转换为 int。

stones = [int(input('input: '))]

推荐阅读