gpt4 book ai didi

python - 按获胜次数对排行榜进行排序

转载 作者:太空宇宙 更新时间:2023-11-03 15:29:42 24 4
gpt4 key购买 nike

我的文本文件的布局如下:名字、姓氏、胜利、失败

jack ,霍弗龙,5,6

扎克,马克,0,11

亚历克斯,霍夫,11,0

dex,gerred,2,9

凯西,comp,1,10

import csv
cho_two=int(input('gg:'))

class_a = open("prac2.txt")
csv_a = csv.reader(class_a)
a_list = []
for row in csv_a:
row[0] = int(row[2])
row[1] = int(row[2])
row[2] = int(row[2])
row[3] = int(row[2])
a_list.append(row[0:3])
if cho_two == 1:
numerical = [[x[0]] for x in a_list]
print("\nCLASS A\nEach students highest by numerical order \n")
for alpha_order in sorted(numerical, reverse=True):
#csv_a.append(alpha_order)
print(alpha_order)

class_a.close()

我试图根据玩家获得的胜利次数来排序排行榜,并过滤掉没有获得一次胜利的玩家,我已经尽可能排序胜利了,但我不知道如何将玩家信息附加到正确的获胜金额。

最佳答案

首先,我将通过将数据读入字典来创建名称 -> 胜利、损失映射。

>>> with open('prac2.txt') as f:
... stats = {}
... for line in f:
... first_name, last_name, wins, losses = line.split(',')
... name = '{} {}'.format(first_name, last_name)
... stats[name] = {'wins': int(wins), 'losses': int(losses)}
...
>>> stats
{'zack macker': {'wins': 0, 'losses': 11}, 'jack hofferon': {'wins': 5, 'losses': 6}, 'dex gerred': {'wins': 2, 'losses': 9}, 'alex hof': {'wins': 11, 'losses': 0}, 'cassy comp': {'wins': 1, 'losses': 10}}

之后,迭代该字典中按获胜次数排序的项目,如果玩家至少获胜一场,则打印出相关信息。看起来是这样的:

>>> sorted_items = sorted(stats.items(), key=lambda x: x[1]['wins'], reverse=True)
>>> for name, info in sorted_items:
... wins = info['wins']
... if wins > 0:
... print('{} {}'.format(name, wins))
...
alex hof 11
jack hofferon 5
dex gerred 2
cassy comp 1

关于python - 按获胜次数对排行榜进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42983011/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com