代码重复打印了太多次

  • 本文关键字:太多 打印 代码 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)
    unsorted_data = list()
    for line in myfile:
        item = line.split(',')
        points = int(item[2]) * 3
        item.append (points)
        if item[2] != 0:
            unsorted_data.append(item)
            sorted_data = sorted(unsorted_data,key=lambda x : x[5], reverse= True)
            for item in sorted_data:
                result = '{0:20} {1:20} {2:20} {3:20} {4:<20}'.format(*item)
                print(result)

嗨,我对 python 很陌生。所以最近在问了另一个关于如何对列表进行排序的问题之后,我现在又遇到了另一个问题。当程序打印我的结果时,它会打印一堆重复的名称。我该如何解决?有没有办法将 .rstrip(( 放入 item[3] 中,因为那里有一个换行转义码,我想摆脱它。一起对列表进行排序。

以下是文件中的几个示例:

Esports,19,8,11
RNGesus,19,7,12
Kes,19,9,10
Magnitude,19,6,13

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)
unsorted_data = list()
for line in myfile:
    item = line.strip().split(',')
    points = int(item[2]) * 3
    item.append (points)
    if item[2] != 0:
        unsorted_data.append(item)
sorted_data = sorted(unsorted_data,key=lambda x : x[4], reverse= True)
for item in sorted_data:
    result = '{0:20} {1:20} {2:20} {3:20} {4:<20}'.format(*item)
    print(result)

您没有清除每行的unsorted_data,因此它每次都使用相同的列表。将其移动到 for 循环内,以便每次迭代创建一个新列表

for line in myfile:
    unsorted_data = [] # can use [] instead of list()

或者只是使用split中的列表(item

(。
sorted_data = sorted(item,key=lambda x : x[4], reverse= True)

也就是说,除非您想要所有数据的列表,否则请将 for 循环移到外部 for 循环之外,以便最后打印所有数据。


至于你想在split之前strip n.

item = line.strip().split(',')

最新更新