我正在尝试对从文件中导入的列表进行从高到低的排序,但似乎没有对它进行排序

时间:2018-11-06 09:41:00

标签: python list file sorting

这是我的代码,用于导入文件,将其添加到列表中并按从高到低的顺序对列表进行排序:

for x in range (1):
            scoresList = [ ] #this is a variable for the list
            file = open("Leaderboard file.txt", "r") #this opens the file as a read file
            file_line = file.readlines() #this then reads the lines
            scoresList.append(file_line) #this then appends the lines to the list
            file.close()
            leaderboard_list = sorted(scoresList, reverse=True) #this is supposed to order the numbers yet it doesnt seem to do anything
            print(leaderboard_list)
            start_menu()

这是打印出来的内容:

[['\n', "35['jerry'] 20['bill']15['Dan']20['billy']"]]

这是从以下位置获取信息的文件:

35['jerry'] 20['bill']15['Dan']20['billy']

1 个答案:

答案 0 :(得分:0)

嗯,那比我预期的要走更长的时间。

with open("file.txt") as f:
    for line in f.readlines():
        new_text = line.strip().replace("[", "").replace("]", "").replace(" ", "").split("'")[:-1]
        new_text = [int(s) if s.isdigit() else s.title() for s in new_text]
        new_text = [(new_text[i],new_text[i+1]) for i in range(0,len(new_text),2)]
        new_text.sort(key=lambda tup: tup[0], reverse=True)

print(new_text)

输出:

[(35, 'Jerry'), (20, 'Bill'), (20, 'Billy'), (15, 'Dan')]

这将返回(每行)已排序的大写元组的列表。如果您的文本格式很重要,则必须从此处进行更多工作。 LMK如果很关键。

帮助:

Collect every pair of elements from a list into tuples in Python

How to sort (list/tuple) of lists/tuples?

Python - How to convert only numbers in a mixed list into float?