2011-05-03 81 views
0

使用函數,我將如何打印從文件中讀取的我的PAY列表的最低,最高和平均值?使用函數打印列表的最低,最高和平均值

try: 
    text_file = open ("Pay.txt", "w") 
    text_file.writelines(Pay) 
    text_file.close() 
except (IOError): 
    print 'Error opening/writing Pay.txt' 

try: 
    text_file= open("Pay.txt","r") 
    PAY_= text_file.readlines() 
    text_file.close() 
    PAY_.sort() 

我從來沒有設立這樣的事,任何人都可以讓我開始?我會提前感謝您的時間內爲您回覆。請記住,我是新來的,我不確切地知道你是如何做的......請耐心等待。

回答

2

。假定你有每行一個數:

numbers = [float(line) for line in open('Pay.txt') if line.strip()] 
if numbers: 
    print 'min', min(numbers) 
    print 'max', max(numbers) 
    print 'avg', sum(numbers)/len(numbers) 
else: 
    print 'file is empty or all lines are blank' 
+0

@約翰·馬金由於,這種結構將右走在我讀的文件,我已經發布? – user735324 2011-05-03 01:54:09

+0

@ user735324:它不是一個「結構」,它*代替您發佈的讀取代碼(除了關閉文件外,它沒有任何用處)。順便說一句,如果你要做的所有嘗試/除了用'錯誤打開/寫入'或類似的替換精確的錯誤信息,那麼不要打擾。 – 2011-05-03 02:12:57

+0

代碼有一個結構,不是嗎?我感謝你的幫助約翰,希望我能給你一些觀點。 – user735324 2011-05-03 02:20:11

相關問題