如何只打印python中的最后一个浮点数?

How to print only the last floating number in python?

我制作了一个脚本来从文件中添加浮点数。每个数字单独一行。 我的结果看起来像这样...... 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

你的循环不正确。假设您的文件有四个浮点值,而您只想添加最后一个。如果 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] is the shortest and most Pythonic.

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

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()

有点不清楚你想做什么。

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

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

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

我认为你的代码格式不正确,这让人很困惑。

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

for item in totallist:
  x = float(item)
  total = total + x
print total
>>> total = sum(float(number) for number in numbers)

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

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