python输入浮点数_如何在python中添加列表中的浮点数?

本文介绍了一种处理包含浮点数的文件内容的方法,通过读取文件中的每一行,将字符串转换为浮点数,计算每个元素的平方,并累加求和。在代码示例中,对原始代码进行了改进,使用了enumerate和列表推导式来提高效率。
摘要由CSDN通过智能技术生成

您的代码有多个问题。你犯的错误是因为你:total=sum(line_str[0:len(element)])

元素是一个整数,它在range()生成的值上循环。

您有total选项并在for循环中打印。您为每个元素而不是每一行调用print,因此无法获得所需的输出。

这个:line_str[0:0]将得到一个空列表,而使用这个:line_str[0:element]将永远不会包含最后一个元素

这是一个只需少量更改即可工作的版本:#Ask the user to input a file name

# file_name=input("Enter the Filename: ") # temporary commented out for easier testing.

file_name = "input.txt"

#Opening the desired file to read the content

infile=open(file_name,'r')

#Importing the math library

import math

#Iterating for the number of lines in the file

for line in infile:

#Converting the file to a list row by row

line_str=line.split()

for element in range(len(line_str)):

line_str[element]=float(line_str[element])

line_str[element]=math.pow(line_str[element],2)

total=sum(li

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值