gpt4 book ai didi

python - 值错误 : could not convert string to float: '1'

转载 作者:太空宇宙 更新时间:2023-11-04 07:08:51 24 4
gpt4 key购买 nike

当我确认我试图转换为 float 的变量确实是一个字符串时,我感到非常困惑(我将在此处显示我的日志):

>>> print ratingXf
'1'
>>> print type(ratingXf)
<type 'str'>
>>> ratingX = float(ratingXf)
ValueError: could not convert string to float: '1'

我计算如下:

rateX, rateY= v.split(',')
ratingXf = (rateX[1:])
ratingX = float(ratingXf)

当我尝试将字符串转换为整数时,出现以下错误:

ValueError: invalid literal for int() with base 10: "'1'"

看起来这应该很简单。但我不明白为什么会出现此错误。任何人都可以发现问题吗?

谢谢!

最佳答案

您有一个嵌套字符串,即 ratingX = "'1'"

对于你的起点 values = ["('1', '1')", "('1', '1')"]

我建议先把它变成你想要的格式:

clean_cell = lambda x: map(float, re.findall(r'\'([0-9]+)\'', x))
values_cleaned = map(clean_cell, values)

# Then iterate
for rating in values_cleaned:
if (len(rating) == 2):
ratingX, ratingY = rating[0], rating[1] # This step is probably not necessary :P
deal_with_ratings(ratingX, ratingY)

关于python - 值错误 : could not convert string to float: '1' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24182956/

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