我需要从字符串类型转换为数字
list = ["-5","4","-3","variable"] # Input
list = [-5,4,-3,"variable"] # epected output
转换负数时遇到问题
list[0]=int(list[0])
ValueError: invalid literal for int() with base 10: '-5'
最佳答案
实际上,我无法重现您的错误,它只能在 python 2.7.13 中工作
>>>int("-5")
>>> -5
在 python 3.4 中
所以,这可能是Python版本问题, 我建议通过从 site 重新安装较新的版本来更新您的 python 版本。 ,它将完美地替换它(软件包不变),除非您使用的是像 anaconda 这样的特殊发行版..
为了处理您的列表(混合字符和数字),请使用:
尝试:除了:
声明。
关于python - 将字符串转换为负数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42102468/