簡體   English   中英

從文件 Python 讀取浮點數

[英]Reading floats from a file Python

我的輸入文件由一堆姓名和成績組成,例如:

里奧·迪卡普里奧______4.5 6.5 7.5
肖恩·康納利______ 3.5 8.5 5.5
[...]

我已經嘗試了所有我能想到的方法,但總是遇到同樣的問題,不能將 str 轉換為 float 以獲得成績。 目標是計算每個人的平均成績。

def average_grade(filename):
infile = open(filename, 'r')
floats = []
names = []
for line in infile:
    words = line.split('_')
    names.append(words[0])
    floats.append(float(words[1]))
infile.close()

print(names)


'''Start'''
average_grade('grades1.txt')

你在這里很不正常。

您的行包含多個下划線_字符。 拆分結果如下:

>>> line = 'Leo DiCaprio______4.5 6.5 7.5\n' #\n added to simulate a line read from a file.
>>> line.split('_')
['Leo DiCaprio', '', '', '', '', '', '4.5 6.5 7.5\n']

要訪問“浮點數”,您需要獲取拆分結果的最后一項。

>>> floats = line.split('_')[-1].strip() #strip out the '\n'
>>> floats
'4.5 6.5 7.5'

但是請注意,這里有多個數字,用空格分隔。 您不能一次全部轉換為浮動,您需要再次拆分它們。

以下行將拆分組成項中的floats ,然后將它們轉換為實際的浮點類型。

>>> numbers = [float(x) for x in floats.split()]
>>> numbers
[4.5, 6.5, 7.5]

現在,我想您可能想用名稱和數字制作一個表格。 最簡單的方法是使用字典。

另外,我建議不要使用floats作為變量名,你很容易將它與float類型混淆。 找到一個更好的名字。 我不確定這些數字是什么,所以我將在下面的代碼中將其稱為numbers ,但您應該選擇一個正確的名稱,例如scoresgrades或它們實際上是什么。

table = {}
with open('grades1.txt', 'r') as f: #use the with statement to open files!
    for line in f:
        words = line.strip().split('_')
        name = words[0]
        numbers = [float(x) for x in words[-1].split()]
        table[name] = numbers

for k,v in table.items():
    print(k, v)

您可以在輸入文件上使用正則表達式,以獲取每個人的成績以及他們的姓名。 所以在文件的每一行上運行一個 for 循環,得到每個人的名字和他們的成績。 獲得成績后,您可以按空格(或分隔它們的任何內容)拆分成績字符串。 這將創建一個列表,您可以使用該列表並將每個成績字符串轉換為浮點數,然后您就知道如何從那里計算平均值:)

讓我知道這是否適合您!

我可以為您提供解決方案,但我想幫助您了解您的工作。

首先,我更改了您的代碼,使其無需單獨的文件即可工作。

這不是你應該做的,但這有助於我將代碼分開。

def average_grade(data):
    floats = []
    names = []
    for line in data:
        words = line.split('_')
        names.append(words[0])
        floats.append(float(words[1]))
    print(names)

average_grade('Leo DiCaprio______4.5 6.5 7.5', 'Sean Connery______ 3.5 8.5 5.5')

當我執行此代碼時,我得到ValueError: could not convert string to float:以及。

但為什么? 那么,讓我們更改代碼:

def average_grade(data):
    floats = []
    names = []
    for line in data:
        words = line.split('_')
        print(words)
        names.append(words[0])
        floats.append(float(words[1]))
    print(names)

average_grade('Leo DiCaprio______4.5 6.5 7.5', 'Sean Connery______ 3.5 8.5 5.5')

這個print(words)給了我們['Leo DiCaprio', '', '', '', '', '', '4.5 6.5 7.5']

我們看到我們分割線的技術還不是很好。

讓我們更加努力:

def average_grade(*data):
    floats = []
    names = []
    for line in data:
        words = line.split('_', 1)
        name = words[0]
        cursor = len(name)
        while line[cursor] == '_':
            cursor += 1
        grades = line[cursor:]
        print((name, grades))
        grades = grades.split()
        print((name, grades))
        grades = [float(i) for i in grades]
        avg = sum(grades) / len(grades)
        print((name, grades, avg))
        names.append(name)
        # Now, what to do with these grades? Do we add them all to the list?
        floats.append(avg)
    print(names)
    print(floats)

average_grade('Leo DiCaprio______4.5 6.5 7.5', 'Sean Connery______ 3.5 8.5 5.5')

現在我們看看grades列表是如何演變的:

('Leo DiCaprio', '4.5 6.5 7.5') # this is our "original", after eliminating the `_`s.
('Leo DiCaprio', ['4.5', '6.5', '7.5']) # This is a list of the strings representung the grades
('Leo DiCaprio', [4.5, 6.5, 7.5], 6.166666666666667) # This is a list of the numbers, along with their average
('Sean Connery', ' 3.5 8.5 5.5') # from here on, the same for Sean
('Sean Connery', ['3.5', '8.5', '5.5'])
('Sean Connery', [3.5, 8.5, 5.5], 5.833333333333333)
['Leo DiCaprio', 'Sean Connery']
[6.166666666666667, 5.833333333333333]

我希望這會有所幫助。

請注意,我在____部分的拆分方式有點“手動”; 使用正則表達式等其他技術肯定會更好。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM