2016-03-14 73 views
-2

因此,我創建了一個存儲在文件中的python遊戲,獲得了一些高分。我希望按字母順序打印文件內容,並按照最高分到最低分打印。我如何按字母順序和按分數排序文件?該文件的內容如下:按字母順序排列文件並按最高到最低排序

角色:James分數:12 ---名:Alex分數:5 ---名稱:馬利 評分:8 ---名稱:迪安分數:16

我感謝任何幫助,謝謝!

+0

'open'和'read'文件,'split'由分隔符生成的字符串,並保存相關結果在字典/或元組列表,然後使用'sorted'。 – MSeifert

+1

請向我們展示您迄今爲止編寫的代碼。 – tdelaney

回答

0

不使用熊貓或什麼,但香草標準Python:

data = "Name:James Score:12---Name:Alex Score:5---Name:Marley Score:8---Name:Dean Score:16" 
stuff1 = filter(lambda _: ":" in _, data.split('---')) 
stuff2 = dict(map(lambda x: (x.split(' ')[0].split(":")[1], x.split(' ')[1].split(":")[1]), stuff1)) 
for name, score in sorted(stuff2.items()): 
    print("{}: {}".format(name, score)) 

for name, score in sorted(stuff2.items(), key=lambda x: x[1]): 
    print("{} - {}".format(score, name))