我被要求设计一个排行榜,
这就是我试过的
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
我希望首先展示获胜最多的人,你能帮忙吗?
答案 0 :(得分:0)
尝试将文件啜饮到列表中:
all_rows = list(reader)
然后对大多数胜利的关键字上的所有行进行排序:
sorted_rows = sorted(all_rows, key=(lambda row: row[2]), reverse=True)
您可能希望堆叠多种排序,或者定义更复杂的密钥,以便您可以在相同数量的胜利中强制执行排序(例如,8场比赛中的7场比100场比赛中的7场胜利更好)。
答案 1 :(得分:-1)
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