我被要求设计一个排行榜,
这就是我尝试过的
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文件如下所示
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我希望它能先显示获胜最多的人,你能帮我吗?
发布于 2017-03-09 01:49:26
尝试将该文件创建为一个列表:
all_rows = list(reader)然后对大多数wins的关键字上的所有行进行排序:
sorted_rows = sorted(all_rows, key=(lambda row: row[2]), reverse=True)您可能希望堆叠多个排序,或定义一个更复杂的键,以便您可以在相同数量的wins中强制排序(例如,8场比赛中的7场比赛胜过100场比赛中的7场比赛)。
发布于 2017-03-09 01:47:07
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 Wonhttps://stackoverflow.com/questions/42678137
复制相似问题