【问题标题】:Using python read floats from a file and store only the decimals使用 python 从文件中读取浮点数并仅存储小数
【发布时间】:2018-04-09 03:52:56
【问题描述】:

所以我在上操作系统课,我的任务是从盖革计数器中收集位。每次盖革计数器报告某些内容时,我都会收到一个时间戳,即 1522187398.44 1522187408.17 每行有一个时间戳。我目前有 22,000 行数字。从这里我将一次取 16 行,并使用这些行创建 8 位,然后将其转换为 ASCII 字符。由于我的时间戳不断增加,我意识到小数点随机高于或低于前一个。目前我正在尝试弄清楚如何保留小数并将它们存储到列表中。我确实探索了一些关于 modf 和从文件读取的问题,但我不断收到一个语法错误,告诉我在第 11 行有一个 TypeError: a float is required。教授要求我使用 python 2.7(我们在作业的后半部分使用 FUSE 文件系统,但这与这个问题无关)。如果有人可以在这部分帮助我,我相信我可以完成任务。我目前的代码在下面。任何帮助将不胜感激。

import math
numbers = []

#Open file with timestamps and store in a list
with open('geiger.txt') as f:
    for line in f:
        numbers.append(map(float, line.split()))

#Keep only the decimals and move decimal place
for convert in numbers:
    numbers = math.modf(convert) * 100

#Check to see if it worked
print(numbers[0:11])

【问题讨论】:

  • 当您说要保留“小数”时,您是指小数点前的数字,还是小数点后的数字?为什么你只想要其中一个?这看起来有点像XY problem

标签: python python-2.7 list file readlines


【解决方案1】:
# import math
# numbers = []

#Open file with timestamps and store in a list
with open('geiger.txt') as f:
    # list comprehension is a a more pythonic way to do this
    # if there is only one timestamp per line there is no point in using split()
    numbers = [line.replace('\n', '') for line in f]
    # for line in f:
    #     numbers.append(map(float, line.split()))

#Keep only the decimals and move decimal place

# since you only need the decimal numbers use split('.') to get them
# for this to work the number type is a string not float
decimal_numbers = [convert.split('.')[1] for n, convert in enumerate(numbers)]

#Check to see if it worked
print(numbers[0:11])
print(decimal_numbers[0:11])

【讨论】:

    【解决方案2】:

    使用您的浮点数列表,您可以执行以下操作。将所有值转换为字符串

    numbers = [10.9854, 8.284729, 7.1248, 8.23784]
    numbers = [str(i) for i in numbers]
    

    然后找到小数点,并提取小数点后的所有数字

    print([i[i.find(".")+1:len(i)] for i in numbers])
    

    ['9854', '284729', '1248', '23784']

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-15
      • 1970-01-01
      • 2012-01-15
      相关资源
      最近更新 更多