繁体   English   中英

将文件中的最高到最低排序

[英]Sort highest to lowest in a file

我是python的新手。 最近,我遇到了一个问题,我想打印一个假游戏的排行榜。

这是我的代码:

myfile = open('Results.txt')
title = '{0:20} {1:20} {2:20} {3:20} {4:20}'.format('Player Nickname','Matches Played','Matches Won','Matches Lost','Points')
print(title)
for line in myfile:
    item = line.split(',')
    points = int(item[2]) * 3
    if points != 0:
        result = '{0:20} {1:20} {2:20} {3:20} {4:<20}'.format(item[0], item[1], item[2], item[3].rstrip(), points)
        print(result)

这是文件中的一些例子

Leeroy,19,7,12
Jenkins,19,8,11
Tyler,19,0,19

我必须使用.rstrip()删除\\ n转义代码,以便格式可以正常工作。

有没有一种非常简单的文件排序方法? 而不是lambda之类的东西,而是真正复杂的东西?

sortedScores = sorted(分数,key = lambda x:x [2] * 3)

你快到了! 您需要做的只是:

sortedScores = sorted(scores, key=lambda x: int(x[2])*3)

您忘记将值乘以整数之前将其转换为整数


这是一种方法-只需在读取文件时添加计算出的点,然后对结果进行排序并打印即可:

data = []

for line in myfile:
    item = line.split(',')
    points = int(item[2]) * 3
    item.append(points)
    data.append(item)

# Now, sort it, the easiest way is to tell it to sort by the last item
import operator
data = sorted(data, key=operator.itemgetter(4), reverse=True)

# or, you can write a lambda!
data = sorted(data, key=lambda x: x[4], reverse=True)

for item in data: 
    result = '{0:20} {1:20} {2:20} {3:20} {4:<20}'.format(*item)
    print(result)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM