【问题标题】:TypeError: bad operand type for unary -: str, how to edit the inputTypeError:一元操作数类型错误-:str,如何编辑输入
【发布时间】:2019-10-17 18:57:30
【问题描述】:

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

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

【问题讨论】:

  • 错误是什么?在你有输入部分之前它工作了吗?
  • stones 是一个字符串,大概类似于"1 2 3"。您需要先将其转换为 int 值列表,例如[int(x) for x in stones.split()].
  • input() 返回一个字符串值。如果您希望它是整数,则必须对其进行转换。
  • Lmao 伙计们,谢谢。有效。我将该行修复为 '''[-int(x) for x in stone.split()]''' 并且效果很好。非常感谢,我是初学者,您的帮助意义重大:)

标签: python python-3.x string list input


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 2013-03-28
    • 2021-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-02
    相关资源
    最近更新 更多