【问题标题】:having trouble converting string to float and adding from list (python)无法将字符串转换为浮点数并从列表中添加(python)
【发布时间】:2021-08-25 00:06:10
【问题描述】:

我正在尝试将这个数字列表(即字符串)转换为浮点数,以便我可以对它们进行分析。但是,我在尝试将它们转换为浮点数时收到错误消息。

这是列表:

temp_gallons = ['404,443.60','367,223.12','388,369.08','352,472.56','386,618.76','3333,929.64 '0.00', '2,817,589']

这是在将它们临时转换为浮点数时添加它们的 for 循环迭代:

Q1_Gallons = 0.0
for i in range(0,2):
  Q1_Gallons = Q1_Gallons + float(temp_gallons[i])

我认为原因是因为每个数字的末尾都有一个空格。所以我尝试使用 for 循环迭代来剥离值:

for i in temp_gallons:
  i.strip(" ")

但是,删除后列表保持不变,我仍然无法将字符串转换为浮点数和/或添加数字。

仅供参考:这些是每个月的值,我正在进行季度储蓄分析,将前三个月、接下来三个月等的值相加。

【问题讨论】:

  • 字符串应该只包含“.”而且只有一次。你的包含“,”
  • 空格不是问题,您可以在字符串的开头和结尾添加任意数量的空白字符:float(' \t 404443.60 \n ') 计算结果为 404443.6

标签: python string floating-point


【解决方案1】:

原因不是尾随空格,而是中间的,

您必须从字符串中删除,,然后转换为float

这里是怎么做的。

temp_gallons = ['404,443.60 ', '367,223.12 ', '388,369.08 ', '352,472.56 ', '386,618.76 ', '333,929.64 ', '326,868.52 ', '257,663.56 ', '0.00 ', '0.00 ', '0.00 ', '0.00 ', '2,817,589 ']

temp_gallons = [float(x.replace(',', '')) for x in temp_gallons]
print(temp_gallons)
[404443.6, 367223.12, 388369.08, 352472.56, 386618.76, 333929.64, 326868.52, 257663.56, 0.0, 0.0, 0.0, 0.0, 2817589.0]

【讨论】:

  • 谢谢!!这行得通。不得不为我的其他元组列表稍微修改它,但算法非常完美,再次感谢您。
【解决方案2】:

首先,您会收到错误,因为字符串中有一个逗号。 Float 无法将逗号转换为浮点数。其次,空间不是问题。假设你有两个字符串 S1 = '123.00 '(有空格), S2 = '12,324324' (有逗号) 。您可以使用 float() 将 S1 转换为浮点数,但不能在 S2 上使用 float(),因为那里有一个“,”。您必须先将其删除。 检查代码:

temp_gallons = ['404,443.60 ', '367,223.12 ', '388,369.08 ', '352,472.56 ', '386,618.76 ',
                '333,929.64 ', '326,868.52 ', '257,663.56 ', '0.00 ', '0.00 ', '0.00 ', '0.00 ', '2,817,589 ']

temp_gallons_float = []

for i in temp_gallons:
    i = i.replace(',', '')
    i = float(i)
    temp_gallons_float.append(i)

print(temp_gallons_float)


# for adding

Q1_Gallons = 0.0

for i in temp_gallons_float:
    Q1_Gallons += i

print(Q1_Gallons)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-20
    • 2021-01-11
    • 2018-04-23
    • 2020-11-19
    • 2015-03-25
    • 2021-12-23
    相关资源
    最近更新 更多