我提供了 Golf.txt 文件的測(cè)試示例以及用于打印結(jié)果的代碼。高爾夫.txt:Andrew53Dougie21打開此文件并打印結(jié)果的代碼(為了保持簡(jiǎn)短,我只有兩個(gè)玩家和兩個(gè)分?jǐn)?shù)golfData = open('golf.txt','r')whichLine=golfData.readlines()for i in range(0,len(whichLine),2): print('Name:'+whichLine[i]) print('Score:'+whichLine[i+1])golfData.close()我可以修改代碼來提取帶有名字的最低玩家分?jǐn)?shù)嗎?我相信我可以不寫列表或字典,但不知道如何。非常感謝幫助/建議。
2 回答

德瑪西亞99
TA貢獻(xiàn)1770條經(jīng)驗(yàn) 獲得超3個(gè)贊
使用min()函數(shù)來實(shí)現(xiàn):
with open('file.txt') as f_in:
min_player, min_score = min(zip(f_in, f_in), key=lambda k: int(k[1]))
print(min_player, min_score)
印刷:
Dougie
21

陪伴而非守候
TA貢獻(xiàn)1757條經(jīng)驗(yàn) 獲得超8個(gè)贊
您可以嘗試這樣的操作:
golfData = open('golf.txt','r')
whichLine=golfData.readlines()
lowest=float('Inf')
Name=''
for i in range(0,len(whichLine),2):
if float(whichLine[i+1])<lowest:
lowest=float(whichLine[i+1])
Name=whichLine[i]
golfData.close()
print(Name)
print(lowest)
添加回答
舉報(bào)
0/150
提交
取消