2017-02-09 66 views
0

您好,这里是python的新增功能,所以最近我正在学习如何编写代码并遇到了这个问题。按从高到低的顺序对列表进行排序

myfile = open('Results.txt') 
    title = '{0:20} {1:20} {2:20} {3:20} {4:20}'.format('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} {4:20}'.format(item[0], item[1], item[2], item[3],point) 
      print(result) 

所以我给了一个文件,我想按照从高到低的顺序排列列表。为了计算积分,我需要完成赢得比赛的金额* 3并从上到下打印一份排序的名单和其他名单。这是清单。

  • 1)马甲,19,7,12
  • 2)Jenker,19,8,11
  • 3)Tieer,19,0,19
  • 5)婴儿老板,19, 7,12

  • 6)Gamered,19,5,14

  • 7)Dogman,19,3,16

  • 8)的Har锁,19,6,13

  • 9)Billies,19,7,12

你怎么办呢?你需要像排序算法吗?

+0

你有什么尝试?你谷歌“蟒蛇排序”?如果是这样,你尝试了什么,你卡在哪里? – Tchotchke

+0

我没有谷歌,我完全不知道如何在python中排序工作没有代码我读了我的理解。 –

回答

0

我会做这样的事情:

scores = [] 
myfile = open('Results.txt') 
for line in myfile: 
    scores.append(line.split(',')) 

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

这将创建listlist(每个子列表是item你叫它) ,然后按第三个元素排序,即总赢。

注:
key=lambda x: x[2]*3是给sorted指定排序标准的参数。对于scores中的每个项目,调用lambda函数。
该项目是一个list,我们返回它的第三个元素乘以三,这是要排序的值。

1

它实际上很简单:

f = open("Results.txt") 
title = ("{:20}" * 5).format(
    "Nickname", 
    "Matches Played", 
    "Matches Won", 
    "Matches Lost", 
    "Points" 
) 
print(title) 
lines = [i.rstrip().split(',') for i in f] # this is a generator expression 
f.close() 
lines.sort(reverse=True, key=lambda x: int(x[2]) * 3) # sorts the list 
# reverse = reversed order. Python normally sorts from small to high. 
print("\n".join('{:20}' * 5).format(*(i + [int(x[2]) * 3]))) 
# f(*l) calls f with l as its arguments 
# (note the plural. so f(*[1, 2, 3]) is the same as f(1, 2, 3)) 
# list1 + list2 concatenates them. 
+2

我想在这里有一点解释会很长... –

+1

@PatrickHaugh新增了它。 – CodenameLambda

+0

非常感谢您的帮助我恐怕我需要做更多的学习才能明白地理解我不会只是复制和粘贴我需要学习才可以学习:) –

相关问题