我试图整理出一个清单,我从一个文件导入从最高到最低,但它似乎没有排序我

2024-04-26 11:20:40 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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']

Tags: 文件theto列表forislinethis
1条回答
网友
1楼 · 发布于 2024-04-26 11:20:40

嗯,那比我想象的要长一点

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')]

这将返回已排序的大写元组列表(每行)。如果您的文本格式是关键的,您将不得不做一些更多的工作从这里。如果它是关键的

帮助来自:

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?

相关问题 更多 >