Python: [TypeError] bad operand type for unary - : ´str´ 解决方法
2020-06-30 11:01
113 查看
TypeError: bad operand type for unary - : ´str´
数组中的第K个最大元素
原题为 : 寻找数组中的第K个最大元素:
输入:nums = [2,3,17,0,-2,5] 和 k = 2
返回:5
报错
这里不讨论堆排序等空间复杂度较低的算法,仅仅用最简单的排序返回时会报错:
def Solution(nums , k) -> int: return sorted(nums)[-k] num = input('num: ?') k = input('Index: ?') print(Solution(num,k))
会产生报错:
TypeError: bad operand type for unary -: 'str'
根据报错的内容,是return 中的 “-k” 的符号判断成了字符类型,我们输出 k的类型:
print(type(k))
它的输出是:
<class 'str'>,自此可以判断是k的输入类型导致sorted函数下标报错。
解决方案
对 k 的输入进行强制类型转换:
k = int(input('Index: ?'))
再次测试没问题:
num: ?2,3,17,0,-2,5 Which: ?2 5
相关文章推荐
- python报错 TypeError: bad operand type for unary +: 'str' 的解决办法
- python TypeError: bad operand type for unary -: 'unicode'
- python TypeError: unsupported operand type(s) for +: 'int' and 'str' [closed]
- Python初学者错误:TypeError: unsupported operand type(s) for +: 'int' and 'str'
- 解决python中TypeError: not enough arguments for format string
- sql server 2000安装中出现:command line option syntax error,type command/? for help解决方法(转)
- python错误TypeError: 'module' object is not callable 的解决方法
- python selenium出现TypeError: __init__() takes 2 positional arguments but 3 were given错误解决方法
- python3.6 TypeError: __init__() got an unexpected keyword argument 'text' 错误的本地解决方法
- 解决python中TypeError: not enough arguments for format stringj
- Command line option syntax error.Type Command /? for help.错误解决方法
- Python ValueError: invalid literal for int() with base 10 实用解决方法
- Python ValueError: invalid literal for int() with base 10 实用解决方法
- 关于python报错:TypeError: unsupported operand type(s) for +=: 'builtin_function_or_method' and 'int'
- 问题:TypeError: only size-1 arrays can be converted to Python scalars 解决方法
- python错误TypeError 'module' object is not callable 的解决方法
- Python BeautifulSoup [解决方法] TypeError: list indices must be integers or slices, not str
- python错误TypeError: 'module' object is not callable 的解决方法
- 真正解决方法之装不上vcredist_x86 提示Command line option syntax error. Type Command /? for Help.
- Python优先权队列出现TypeError: unorderable types 解决方法