我必須撰寫一個 Python 函式來記錄不同日子的溫度。同一天的溫度存盤在同一行。第一天被認為是第 1 天,檔案的每個后續行按順序記錄接下來的幾天(例如第 3 行資料是從第 3 天開始收集的) )。如果某一天沒有收集到資料,那么整行將是空白的。例如,文本檔案包含 6 天的以下輸入:
23 24.5
25
22.25 22.5
23.4
25.2 20.0
該檔案包含 6 天收集的資料。
我要定義一個函式temp_record,它以檔案名作為引數。它從引數檔案中讀取資料并分析溫度。該函式應回傳每天平均溫度的串列。例如,該函式為上述文本檔案回傳以下串列:
[23.75, 25.0, 22.375, 0, 23.4, 22.6]
我寫了一個代碼,但它似乎不適用于所有案例型別,我不確定出了什么問題。有人可以幫忙嗎?
這是我寫的代碼:
def temp_record(filename):
input_file = open(filename,'r')
contents = input_file.read().split("\n")
sum_val = 0
lis = []
for string in contents:
split_str = string.split(" ")
for i in range(len(split_str)):
if split_str[i] == '':
split_str[i] = 0
else:
split_str[i] = float(split_str[i])
ans = (sum(split_str)/len(split_str))
if ans == 0.0:
ans = 0
lis.append(ans)
return lis
太感謝了!
這是我提交代碼時提交頁面顯示的螢屏截圖的鏈接。 https://i.stack.imgur.com/MUPYg.png
uj5u.com熱心網友回復:
當您這樣做時,contents = input_file.read().split("\n")您會在contents串列中獲得一個額外的元素,該元素被計算為 0。
你可以像這樣解決這個問題:
def temp_record(filename):
input_file = open(filename, 'r')
# read all lines
contents = input_file.readlines()
sum_val = 0
lis = []
for string in contents:
# lines end in \n use rstrip to remove it
split_str = string.rstrip().split(" ")
for i in range(len(split_str)):
if split_str[i] == '':
split_str[i] = 0
else:
split_str[i] = float(split_str[i])
ans = (sum(split_str) / len(split_str))
if ans == 0.0:
ans = 0
lis.append(ans)
return lis
但這可以更短:
def temp_record(filename):
result = []
with open(filename, 'r') as fp:
for line in fp:
temps = line.split()
avg_temp = sum(map(float, temps)) / len(temps) if temps else 0
result.append(avg_temp if avg_temp > 0 else 0)
return result
如果您想玩 Golfcode,甚至更短:
def temp_record2(filename):
with open(filename, 'r') as fp:
return list(map(lambda x: x if x > 0 else int(x), [sum(map(float, line.split())) / len(line.split()) if line.split() else 0 for line in fp]))
uj5u.com熱心網友回復:
也許失敗的隱藏測驗是這樣的輸入:
-1 1
0
30
前兩天確實記錄了溫度,但它們的平均值為 0。按照對所有其他平均值使用浮點數的格式,平均值應該是0.0,而不是0(因為這意味著當天沒有收集到溫度,而實際上是)。
如果這是問題,可以修復:
def temp_record(filename):
input_file = open(filename,'r')
contents = input_file.read().split("\n")
sum_val = 0
lis = []
for string in contents:
split_str = string.split(" ")
for i in range(len(split_str)):
if split_str[i] == '':
split_str[i] = 0
else:
split_str[i] = float(split_str[i])
ans = (sum(split_str)/len(split_str))
if string == '':
ans = 0
lis.append(ans)
return lis
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/406015.html
標籤:
