首页 > 解决方案 > (Python) 使用文件输入和输出按销售额对电影进行排序

问题描述

我的程序“在技术上”有效……但必须有更好的解决方案。

所以在一个文本文件中有一个随机顺序排列的前 500 部电影列表。

Avatar    71245151
Star Wars    92815125
Matrix    4215151  ......

问题是创建一个函数,将文本文件作为输入,并将排名前 500 的电影按顺序(最高到最低销售额)写入另一个文件。

def sort_films(file_name, destination_file):
    open_file = open(file_name, "r")    #Read the file
    movie_list = []

    for line in open_file:
       movie_list.append(line.split("\t")) #Since "\t" exists, split

    open_file.close()    

在这里,movie_list 看起来像这样

movie_list = [['Avatar', '5241521\n'], ['Star Wars', '9512512'], ....]

由于我们在将数字字符串转换为整数并将数字从高到低排序时不希望换行,这就是我所做的。我还将数字放在每个列表的前面,因为 sort() 按字母顺序对电影进行排序,这不是我想要的。

    for movie in movie_list:
        movie.insert(0, movie[1])
        movie.pop()
    for movie in movie_list:
        movie[0] = int(movie[0].replace("\n", ""))


    movie_list.sort(reverse = True)

现在我要写文件了。

    open_file = open(destination_file, "w")

    string = ""

我添加了一个换行符,因为我们想在另一个文本文件中显示电影的样子(在将销售额转换为字符串之后。)

由于订单最初是[电影,销售],因此更改了位置。

    for movie in movie_list:
        movie[0] = str(movie[0]) + "\n" 
        movie.insert(0, movie[1])
        movie.pop()

然后我们之前有“\t”,所以我加入了电影的名称和销售量。

        string += "\t".join(movie)

    open_file.write(string)

    open_file.close()   

sort_films("top500.txt", "top500result.txt")

我觉得有一种方法可以将数字从高到低排序,而无需更改列表中的索引(位置)......

如果有人可以帮助我,将不胜感激。

标签: pythonpython-3.xfileio

解决方案


movie_list.sort(key=lambda x: x[1])

如此处示例: 基于第二个参数对元组进行排序


推荐阅读