所以,我正在學習 Python 并有這些有趣的作業
我有兩個檔案rating_strikers1.txt,并rating_strikers2.txt在那里他們評為一些足球前鋒從1到99。
文本檔案中rating_strikers1有這個:
Kane ; 85
Aubameyang ; 80
Werner ; 76
Lukaku ; 88
文本檔案“ rating_strikers2”中有這個:
Kane ; 85
Aubameyang ; 80
Werner ; 76
Lukaku ; 88
Lacazette ; 75
Antonio ; 80
我必須將這些檔案讀入 adict并檢查 akey是否也在另一個檔案中。但是,我也只需要列印 80 或更高的評分。
我想定義一個函式來讀取檔案并回傳一個dict.
預期輸出:列印出“rating_strikers1.txt”和“rating_strikers2.txt”均評分為 80 或更高的所有前鋒。
uj5u.com熱心網友回復:
嘗試這個:
def myfunc():
files = list()
files.append(open('rating_strikers1.txt', 'r'))
files.append(open('rating_strikers2.txt', 'r'))
outdict = dict()
for file in files:
for line in file.read().splitlines():
try:
key, value = line.split(" ; ")
if key not in outdict.keys():
outdict[key] = list()
outdict[key].append(int(value))
except:
pass
for key, value in outdict.items():
if all(x >= 80 for x in value):
print(key, value)
myfunc()
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/357681.html
標籤:Python python-2.7 文件 字典
