gpt4 book ai didi

python - 两个 float 抛出 TypeError : unsupported operand type(s) for +: 'float' and 'str'

转载 作者:行者123 更新时间:2023-11-28 22:29:20 25 4
gpt4 key购买 nike

我遇到了以下代码行的问题:

underground['distributed_load_C'] = float(ugLineList[21])*1000 + ('+' if float(ugLineList[24]) >= 0.0 else '-') + abs(float(ugLineList[24]))*1000j

从 ugLineList 中提取的原始值是字符串,我尝试在添加之前将它们类型转换为 float 。即使我尝试对它们进行类型转换,我也会收到以下错误:

TypeError: unsupported operand type(s) for +: 'float' and 'str'

我已经尝试在这条语句之前对它们进行类型转换,并检查代码片段是否真的是 float : print type(float(ugLineList[21])*1000), type(float(ugLineList[24]))---> <type 'float'> <type 'float'>

我真的很困惑这里发生了什么,所以非常感谢任何帮助。

谢谢!!

最佳答案

上面的注释(您根据 ugLineList[24] 的值添加字符串“+”或“-”)完全正确。假设您打算添加或减去

abs(float(ugLineList[24]))*1000j

根据对 if 语句的评估,您可以执行以下操作:

res = float(ugLineList[21])*1000
if float(ugLineList[24]) >= 0.0:
res += abs(float(ugLineList[24]))*1000j
else:
res -= abs(float(ugLineList[24]))*1000j
underground['distributed_load_C'] = res

希望对你有帮助

关于python - 两个 float 抛出 TypeError : unsupported operand type(s) for +: 'float' and 'str' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43097442/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com