我的文本文件的布局如下:名字,姓氏,胜利,损失
插孔,hofferon,5,6-
扎克,macker,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()
我试图通过玩家获得多少胜利来排序排行榜,并过滤掉没有获得过一次胜利的玩家,我已经获得了订购胜利但我不知道如何将玩家信息附加到正确的赢额。
答案 0 :(得分:1)
首先,我要创建一个名称 - >通过将数据读入字典来获胜,损失映射。
>>> 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
答案 1 :(得分:0)
以下代码使用python OrderedDict
Unsorted
dex: 2
cassy: 1
alex: 11
jack: 5
zack: 0
Sorted
alex: 11
jack: 5
dex: 2
cassy: 1
zack: 0
输出:
\N
答案 2 :(得分:0)
如果您没有任何重复的数据科学方法,我建议使用pandas
import pandas as pd
leaderboard = pd.read_csv('leaders.txt', header=None)
#filter those who don't have any wins (0 in third column)
leaderboard = leaderboard[leaderboard[2] > 0]
#sort by third column
leaderboard.sort(2, ascending = False)
如果您想保存csv,只需执行leaderboard.to_csv('ordered.txt', header=False)