首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python:排行榜

Python:排行榜
EN

Stack Overflow用户
提问于 2017-03-09 01:35:45
回答 2查看 693关注 0票数 0

我被要求设计一个排行榜,

这就是我尝试过的

代码语言:javascript
复制
def leader():

    file = open ("res.txt","r")
    reader = csv.reader(file)
    print (("{:20s}{:20s}{:20s}{:20s}".format("\nPlayer","Matches played","Won","Lost")))
    won = 100

    for r in reader:
        won = won-1
        if r[2] == str(won):
           print (("{:20s}{:20s}{:20s}{:20s}".format(r[0],r[1],r[2],r[3])))



    file.close()

我的csv文件如下所示

代码语言:javascript
复制
Leeroy,19,7,12
Jenkins,19,8,11
Tyler,19,0,19
Napoleon Wilson,19,7,12
Big Boss,19,7,12
Game Dude,19,5,14
Macho Man,19,3,16
Space Pirate,19,6,13
Billy Casper,19,7,12
Otacon,19,7,12
Big Brother,19,7,12
Ingsoc,19,5,14
Ripley,19,5,14
M'lady,19,4,15
Einstein100,19,8,11
Dennis,19,5,14
Esports,19,8,11
RNGesus,19,7,12
Kes,19,9,10
Magnitude,19,6,13

我希望它能先显示获胜最多的人,你能帮我吗?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-03-09 01:49:26

尝试将该文件创建为一个列表:

代码语言:javascript
复制
all_rows = list(reader)

然后对大多数wins的关键字上的所有行进行排序:

代码语言:javascript
复制
sorted_rows = sorted(all_rows, key=(lambda row: row[2]), reverse=True)

您可能希望堆叠多个排序,或定义一个更复杂的键,以便您可以在相同数量的wins中强制排序(例如,8场比赛中的7场比赛胜过100场比赛中的7场比赛)。

票数 0
EN

Stack Overflow用户

发布于 2017-03-09 01:47:07

代码语言:javascript
复制
keys = ["Player","Matches played","Won","Lost"]

# read file
with open("res.txt") as f:
    content = f.readlines()
# you may also want to remove whitespace characters like `\n` at the end of each line and 
# split it by ',' then form a dictionary out of it 
content = [dict(zip(keys,x.strip().split(','))) for x in content]
# sort the above list of dicts in decreasing orde.
final_result = sorted(content, key=lambda k: k['Won'], reverse=True)

print final_result# sorted By score
# first element is the one with highest Won value
print final_result[0] # highest Won
票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42678137

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档