[英]Obtaining an average from if statement Python 3
好吧,我一切都明白了。 但是現在,我嘗試使用if語句告訴循環從小於22 mpg的車輛中獲取平均mpg(來自.txt文件),然后將其平均並輸出IDLE。 我覺得我應該在循環之前運行if語句。 我只是不確定我真正需要改變什么。 我認為我應該能夠對保存文本文件數據的變量進行切片。 無論如何,這是我的代碼。 有人可以幫助我了解我做錯了什么嗎?
def cityGasGuzzler():
# Input:that assigns a text file to a value and provides other definition
values
cityGuzz = open("carModelData_city.","r")
# Process: For loop to get average of gas guzzling city street driving
vehicles
for line in cityGuzz:
# Process: Uses if statement to get the average of lower mpg or gas guzzlers
if cityGuzz[0:-1] < 22:
sum = sum + eval(line)
count = count + 1
avrg = sum / count
# Output: using the round function to get average to the 2nd decimal place
# and prints string and rounded variable to IDLE.
print("The average city MPG is,", round(avrg, 2))
cityGasGuzzler()
為了明確起見,我的主要目標如下,從文本文件中獲取小於22的數值,將其取平均值,然后將平均值輸出到IDLE。
您的問題是您要在循環的每次迭代中嘗試按數量划分。 另外,您的代碼中有幾個錯誤。 試試看
sum = 0.0
quantity = 0
with open('file.txt', 'r') as f:
for line in f.readline():
if line.isdigit():
sum += float(line)
quantity += 1
average = sum/quantity
print average
如果我正確理解了這個問題,那么您遇到的問題是:
if cityGuzz[0:-1] < 22:
這樣做有多種原因,其中不僅僅因為cityGuzz
是文件對象,還不是當前行。 您需要先將當前行轉換為數字,然后再將其與22
類的數字進行比較。
嘗試這樣的事情:
total = 0 # renamed to avoid masking the builtin sum function
count = 0
for line in cityGuzz:
mpg = float(line)
if mpg < 22:
total += mpg
count += 1
average = total / count
我將sum
重命名為total
因為sum
是內置函數的名稱。 實際上,替換顯式循環以從文件中添加值可能是有用的。 這是平均值計算的替代實現:
guzzlers = [mpg for mpg in map(float, cityGuzz) if mpg < 22]
average = sum(guzzlers) / len(guzzlers)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.