2016-11-08 78 views
-1

我目前正在學習大學計算機科學的初級水平。我真的不知道如何從打開的文件中獲得某些信息......如果有機會,有人可以教我如何執行此代碼嗎?如何在python中使用for循環從文件中獲取特定列表?

def get_month_temp(openfile, m): 
    ''' 
    (file, int) -> listReturn a list of temperatures for the 
    month mo for all years with data in 
    open_file, where mo is an integer between 
    0 and 12, representing January to December, 
    respectively. 
    >>>got_month_temp("temperature.csv", 1) 
    [24.7, 16,1, 10.4, 21.5, 19.1, 14.0, 8.4, 11.2, 13.4, 22.5, 17.6, 20.4] 
    ''' 
    openfile = open_temperature_file(filename) 

這是我所說的「temperature.csv」文件。

Average monthly temperatures in Dubuque, Iowa, 
    January 1964 through december 1975, n=144 

    24.7,25.7,30.6,47.5,62.9,68.5,73.7,67.9,61.1,48.5,39.6,20.0 
    16.1,19.1,24.2,45.4,61.3,66.5,72.1,68.4,60.2,50.9,37.4,31.1 
    10.4,21.6,37.4,44.7,53.2,68.0,73.7,68.2,60.7,50.2,37.2,24.6 
    21.5,14.7,35.0,48.3,54.0,68.2,69.6,65.7,60.8,49.1,33.2,26.0 
    19.1,20.6,40.2,50.0,55.3,67.7,70.7,70.3,60.6,50.7,35.8,20.7 
    14.0,24.1,29.4,46.6,58.6,62.2,72.1,71.7,61.9,47.6,34.2,20.4 
    8.4, 19.0,31.4,48.7,61.6,68.1,72.2,70.6,62.5,52.7,36.7,23.8 
    11.2,20.0,29.6,47.7,55.8,73.2,68.0,67.1,64.9,57.1,37.6,27.7 
    13.4,17.2,30.8,43.7,62.3,66.4,70.2,71.6,62.1,46.0,32.7,17.3 
    22.5,25.7,42.3,45.2,55.5,68.9,72.3,72.3,62.5,55.6,38.0,20.4 
    17.6,20.5,34.2,49.2,54.8,63.8,74.0,67.1,57.7,50.8,36.8,25.5 
    20.4,19.6,24.6,41.3,61.8,68.5,72.0,71.1,57.3,52.5,40.6,26.2 
+1

以及如何' 「temperature.csv」'內容是什麼樣子? – RomanPerekhrest

+0

@RomanPerekhrest我剛剛添加了「temperature.csv」文件。非常感謝您的幫助!! – Jason

+0

@ juanpa.arrivillaga嗨,謝謝你的回覆!是的,我需要使用for-loops!你能幫我寫這個程序嗎? – Jason

回答

0

根據您的預期輸出結果,每個月的所有溫度數據已排列在垂直列中。
使用下面的方法與csv.reader對象,split功能和列表理解

def get_month_temp(openfile, m): 
    if m not in range(1, 13): 
     raise ValueError('incorrect month number!') 

    with open(openfile) as fh: 
     reader = csv.reader(fh, delimiter=',') 
     lines = [l.strip().split(',')[m-1] for l in fh] 
     print(lines) 


get_month_temp("data/temperature.csv", 1) 

輸出:

['24.7', '16.1', '10.4', '21.5', '19.1', '14.0', '8.4', '11.2', '13.4', '22.5', '17.6', '20.4'] 
相關問題