【问题标题】:How to print only the last floating number in python?如何只打印python中的最后一个浮点数?
【发布时间】:2015-02-25 11:11:13
【问题描述】:

我编写了一个脚本来从文件中添加浮点数。每个数字在其自己的行中分隔。 我的结果看起来像这样...... 412.2693 412.4593 419.9593 我只想显示 419.9593 号码。

这是我到目前为止写的最后一部分:

infile.close()
for theitem in totallist:
#       print theitem
    a = float(theitem)
#       print a
        total = 0.0
        for item in totallist:
                x = float(item)
                total = total + x
                print total

【问题讨论】:

  • 您可以在for 循环范围之外声明x,然后您可以在for 循环范围之外声明print x
  • 数字是否存储在列表中,例如:my_lst = [412.2693, 412.4593 419.9593,..]
  • EdChum 提案会起作用,但在性能方面,最好只访问列表的最后一个位置,而不是遍历所有元素。
  • 不,它们不在列表中。它们在每一行上分开一个。有没有办法让它们进入列表?然后我可以在列表中执行 [-1]
  • 什么是totallist 是列表还是文件对象?

标签: python point floating


【解决方案1】:

有点不清楚你想做什么。

我假设你有一个每行都有一个浮点数的文件,你想对它们求和并打印结果。

如果你已经有一个包含行的totallist,那么你必须先将字符串转换为float,然后你可以使用sum函数和print结果:

total = sum(map(float, totallist))
print total

【讨论】:

  • 谢谢!这就是我需要的!
  • 刚刚做到了!根本不需要最后的循环
  • 但您的问题与此解决方案不符。请编辑主题以匹配它。
【解决方案2】:

你循环不正确。假设您的文件有四个浮点值,并且您只想要最后一个添加。如果 totallist 包含您的文件结果值。

totallist = ["46.78","67.89","67.677","67"]
for theitem in totallist:
    a = float(theitem)
    total = 0.0
    for item in totallist:
        x = float(item)
        total = total + x

print total

空闲:

>>> ================================ RESTART ================================
>>> 
249.347
>>> 

否则,您可以插入列表并获取最后一个元素。

some_list[-1] 是最短和最 Pythonic 的。

【讨论】:

    【解决方案3】:

    假设每行只能包含数字和空格,您可以使用下面的代码。它检查每一行,只存储数字(如果存在)。然后你可以像你提到的那样对其进行切片。

    my_lst = []
    with open('my_text_file.txt', 'r') as opened_file:
    
        for line in opened_file:
            number = line.strip()
    
            if number:
                my_lst.append(number)
    
    print my_lst
    

    注意with open() as会自动关闭文件,比open()更可取。

    【讨论】:

      【解决方案4】:

      我认为您的代码在这里的格式不正确,这相当令人困惑。

      您只需要在循环之外打印总计。

      for item in totallist:
        x = float(item)
        total = total + x
      print total
      

      【讨论】:

        【解决方案5】:
        >>> total = sum(float(number) for number in numbers)
        

        【讨论】:

          【解决方案6】:

          如果你想要一个列表(来自一个文件): lines = open(filename,"r").readlines()

          如果要显示列表中的最后一项: 打印(行[-1])

          【讨论】:

            猜你喜欢
            • 2014-01-07
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2020-12-09
            • 2020-01-04
            • 1970-01-01
            • 2021-01-19
            • 2017-12-27
            相关资源
            最近更新 更多