简体   繁体   English

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

[英]How to add the floating numbers in a list in python?

How do I add the sum of the squares in the input file? 如何在输入文件中相加平方和

Input file is a txt file and is shown below: 输入文件是一个txt文件,如下所示:

10 9 8 7 1 2 3 4
3 -4 1 -2
0.743 -12.3 5.3333 3
-3.3

Hence the output may look like this; 因此,输出可能看起来像这样;

324.0
30.0
189.28613789000002
10.889999999999999

I can't add the floating numbers using sum as it displays an error, so any help would be much appreciated. 我无法使用sum将浮点数相加,因为它会显示错误,因此我们将不胜感激。

Here is my code: 这是我的代码:

#Ask the user to input a file name
file_name=input("Enter the Filename: ")

#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(line_str[0:len(element)])
        print(total)

There are multiple problems with your code. 您的代码有多个问题。

  1. The error you got is because you do: 您得到的错误是因为您这样做:

     total=sum(line_str[0:len(element)]) 

    and element is an integer as it loops over the the values range() generates. 当循环遍历range()生成的值时,element是一个整数。

  2. You have the total isation and print in the for loops. 您具有total的情况,并在for循环中打印。 You call print for every element, not for every line, so you cannot get the output that you need. 您为每个元素而不是每一行都调用print ,因此无法获得所需的输出。

  3. This: line_str[0:0] will get you an empty list, and your use of this: line_str[0:element] will never include the last element 此: line_str[0:0]将为您提供一个空列表,而您对此的使用: line_str[0:element]将永远不会包含最后一个元素

This is a version that works with minimal changes: 这是一个版本,只需最少的更改即可使用:

#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(line_str[0:element+1])
    print(total)

This gives: 这给出:

324.0
30.0
189.28613789000002
10.889999999999999

but can be much improved upon: 但可以在以下方面进行很多改进:

  • use spaces around = in assignments 在作业中在=周围使用空格
  • don't use for .... range(somelist): and then index somelist . 不要for .... range(somelist):然后索引somelist Instead use enumerate. 而是使用枚举。
  • combine the conversion to float with splitting the line 结合转换以浮动和分割线
  • use a space after '#' in comments 在注释中的“#”后使用空格

Something along these lines: 遵循以下原则:

# Ask the user to input a file name
# file_name=input("Enter the Filename: ")
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 and convert to float
    line_str = [float(x) for x in line.split()]

    for idx, element in enumerate(line_str):
        line_str[idx] = math.pow(element,2)
    total = sum(line_str)
    print(total)
for line in infile:
    numbers = map(float, line.split())
    squares = (i ** 2 for i in numbers)
    print(sum(squares))

I think you are misunderstanding the split function and what it does. 我认为您误解了分割功能及其作用。

$ python
Python 3.5.1 |Anaconda 4.0.0 (64-bit)| (default, Feb 16 2016, 09:49:46) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> line = "10 9 8 7 1 2 3 4"
>>> line_str = line.split()
>>> line_str
['10', '9', '8', '7', '1', '2', '3', '4']

split takes the string and at every space splits the string into substrings, each substring is an element in the list split接受字符串,并在每个空格处将字符串拆分为子字符串,每个子字符串都是列表中的一个元素

Your loop code is behaving like you need to find the individual numbers in the string. 您的循环代码的行为就像您需要在字符串中查找单个数字一样。

>>> 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(line_str[0:len(element)])
...         print(total)
...
Traceback (most recent call last):
  File "<stdin>", line 4, in <module>
TypeError: object of type 'int' has no len()

So now lets loop through the list (using enumerate as suggested above) and convert each element to a float, square it using math.pow and store it back in the same list. 现在,让我们遍历列表(使用上面建议的枚举)并将每个元素转换为浮点数,使用math.pow将其平方并存储回相同的列表中。 The you can pass the list to sum() to get your total. 您可以将列表传递给sum()以获得总计。 The beauty of Python is that you can always drop down into the interpreter and run your commands one by one and investigate the results. Python的优点在于,您始终可以进入解释器并逐一运行命令并研究结果。

>>> import math
>>> line = "10 9 8 7 1 2 3 4"
>>> line_str = line.split()
>>> line_str
['10', '9', '8', '7', '1', '2', '3', '4']
>>> for i,value in enumerate(line_str):
...   fvalue = float(value)
...   line_str[i] = math.pow(fvalue,2)
...
>>> line_str
[100.0, 81.0, 64.0, 49.0, 1.0, 4.0, 9.0, 16.0]
>>> sum(line_str)
324.0
>>>

Now the question you may one day ask yourself is, why did I want to use math.pow(fvalue,2) when I could have just done fvalue**2 or even fvalue*fvalue 现在,您可能有一天会问自己一个问题,为什么我本来可以做fvalue**2甚至fvalue*fvalue时候还是想使用math.pow(fvalue,2)

When you are ready you can read about it here Exponentials in python x.**y vs math.pow(x, y) 准备就绪后,您可以在此处阅读有关python x。** y与math.pow(x,y)的指数的信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM