简体   繁体   English

如何遍历包含 Python 中浮点数列表的文件?

[英]How do I iterate through a file containing a list of floating point numbers in Python?

I need to write a program that reads a file containing a list of floating-point numbers and counts how many of those numbers are larger than a user-specified threshold.我需要编写一个程序来读取包含浮点数列表的文件并计算这些数字中有多少大于用户指定的阈值。

numbers.txt -数字.txt -

  • 5.0 5.0
  • 15.0 15.0
  • 25.0 25.0

This is my python code -这是我的 python 代码 -

in_file = open("numbers.txt", "r")
number = float(in_file.read())  # error in python
user_input = float(input("Threshold: "))
if number > user_input:
    print(number)
in_file.close()

Python is unable to convert the string to a float because the numbers have a new line after each number and python is trying to convert that into a float. Python 无法将字符串转换为浮点数,因为数字在每个数字后都有一个新行,并且 python 正在尝试将其转换为浮点数。 I tried to change line 2 in my code to add a strip method but it still comes up with the same error.我试图在我的代码中更改第 2 行以添加一个 strip 方法,但它仍然出现相同的错误。

for line in open("numbers.txt", "r"):
    line = line.replace("\n","")
    num = float(line)

im sure you can continue from here..我确定你可以从这里继续..

Try this:尝试这个:

with open('numbers.txt') as fp:
    lst = [float(line.strip()) for line in fp if line.strip()]
    user_input = float(input("Threshold: "))
    for num in lst:
        if num > user_input:
            print(num)

You can try this workaround你可以试试这个解决方法

inputdata = []
with open('data.txt') as f:
    for row in f:
        try:
            number = float(row)
            inputdata.append(number)
        except:
            pass

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

相关问题 如何在python中遍历浮点数列表 - How to iterate through a list of floating point numbers in python 如何在此代码中迭代浮点数列表 - How to iterate over a list of floating point numbers in this code 如何遍历字符串格式的数字列表? - How do I iterate through a list of numbers in string format? 如何遍历列表的特定对 - Python - How do I iterate through through specific pairs of a list - Python 如何修复Python函数以遍历目录中的JSON文件列表并合并为单个JSON文件 - How do I fix a Python Function to iterate through a list of JSON files in a directory and merge into a Single JSON file 如何在python中使用整数运算将分数转换为浮点数? - How do I use integer arithmetic to convert fractions into floating point numbers in python? 我如何使用 Python 和 Selenium 遍历 webelements 列表? - How do i iterate through a webelements list with Python and Selenium? 如何使用Python在二进制文件中查找浮点数? - How to find floating point numbers in binary file with Python? Python从列表中打印浮点数 - Python printing floating point numbers from a list 在Python中:如何使用指定数量的数字在文件中编写浮点数? - In Python: How can I write floating point numbers in a file using a specified number of figures?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM