如果你想獲得幻想,試試這個:
def parse_file(f):
competitors = []
for line in f:
last, first, year, medals, _ = line.strip(), next(f).strip(), next(f).strip(), next(f).strip(), next(f)
competitors.append({"last":last, "first":first,
"year":year, "medals":medals})
return competitors
def count_by_year(year, competitors_dict):
# year must be a string
year = str(year)
return sum(competitor['medals'] for competitor in competitors_dict if competitor['year'] == year)
def years_by_athlete(firstname, lastname, year, competitors_dict):
for competitor in competitors_dict:
if competitor['first'] == firstname and \
competitor['last'] == lastname and \
competitor['year'] == year:
return competitor['medals']
return None
if __name__ == "__main__":
with open('path/to/your/file', 'r') as f:
competitors = parse_file(f)
num_medals_by_year = count_by_year(1900, competitors)
num_medals_by_athlete = years_by_athlete("DARIA", "PRATT", "1900", competitors)
記住,文件對象在Python迭代器,所以如果你正在讀文件描述如下:
This is the first line
This is the second line
This is the third line
This is the fourth line
This is a blank line
那麼你可以做
for line in file:
firstline = line
secondline = next(file)
thirdline = next(file)
fourthline = next(file)
_ = next(file)
內置的next
推進迭代器。代碼以5行塊的形式貫穿整個文件,將最後一行分配給_
(這是「我們不使用這個」的常見Python成語,例如for _ in range(10)
做了10次)。然後我們建立一個字典列表,以便稍後參考。這比我們每次查看文件時讀取文件要快得多。我們使用strip
(除了我們扔掉的線以外,因爲......爲什麼要打擾?)來刪除尾隨的空格。這包括在每行末尾的換行符(如匹配的文件讀取This is the first line
準確,你就必須尋找"This is the first line\n"
)
然後使用內置sum
功能,我們使用一臺發電機表達式如果'year'
值與我們給出的值相符,則給予每個'medals'
值。這將展開到:
s = 0
for competitor in competitors_dict:
if competitors_dict['year'] == year:
s += competitors_dict['medals']
return s
至於你的第二個功能,你需要的是一系列if
條件。通過competitors_dict
迭代並確保'first'
,'last'
和'year'
字段都與您的參數匹配,然後返回'medals'
字段。就這麼簡單:)
第一個'break'執行後的代碼能執行嗎? – 101 2014-09-19 00:04:02
爲什麼不'如果行==年? – 2014-09-19 00:08:29
我認爲行是必要的計數器,我將不得不增加去下一行? – darksoulsfan 2014-09-19 00:09:54