【问题标题】:why 'float' object is not iterable为什么“浮动”对象不可迭代
【发布时间】:2021-03-01 01:46:29
【问题描述】:

我是初学者,所以我会尽可能多地练习。在下面的代码中,我必须从包含一百行和总和的文本文件中提取数字。我写了下面的代码,输出消息是:float object are not iterable。 我将不胜感激帮助和建议。

fname = 'mbox-short.txt'
fh = open(fname,"r")

count = 0
for line in fh :
    line = line.rstrip()
    if not line.startswith('X-DSPAM-Confidence:') : continue
    count = count + 1
    #print(count)

    colonn_pos = line.find(':')
    fnum = line[colonn_pos+1:]
    numbers = float(fnum)
    #print(numbers)

total = 0
for values in numbers :
    if values < 1 :
        total = total + values
    print(total)

下面的数字输出到总和:

0.8475 0.6178 0.6961 0.7565 0.7626 0.7556 0.7002 0.7615 0.7601

【问题讨论】:

  • 为什么浮动对象是可迭代的?你会期待什么? for something in 1.0:?

标签: for-loop sum floating-accuracy


【解决方案1】:

您将 numbers 设置为单个浮点对象,该对象不可迭代。

如果您想遍历第一个循环生成的所有浮点数,您应该创建一个名为“numbers”的列表并append() 每个单独的浮点数。

numbers = []
count = 0
for line in fh :
    line = line.rstrip()
    ...
    numbers.append(float(fnum))

total = 0
for value in numbers:
...

我还要指出,迭代一个列表以生成一个你再次迭代的列表是多余的,所以我实际上将其更改为:

count = 0
total = 0.0
for line in fh :
    line = line.rstrip()
    ...
    num = float(fnum)
    if num < 1:
        total += num
    print(total)

【讨论】:

    猜你喜欢
    • 2021-05-16
    • 2023-03-09
    • 2014-03-16
    • 1970-01-01
    • 2011-12-28
    • 2018-05-15
    • 1970-01-01
    • 1970-01-01
    • 2020-10-22
    相关资源
    最近更新 更多