(Python)使用文件输入和输出按销售排序影片

问题描述 投票:0回答:4

我的程序“技术上”有效......但是必须有一个更好的解决方案。

因此,文本文件中有随机顺序排名前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")

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

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

python python-3.x file io
4个回答
0
投票

您听起来希望能够通过内部列表(销售)内的元素对列表列表进行排序。也许你可以尝试这样的事情:

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

应该这样做


0
投票

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

例如:Sort tuples based on second parameter


0
投票

我建议你上课。在您的情况下,您需要一个具有一个字符串和一个整数的类。从那时起,一切都会变得更容易。你将只有一个完整的对象阵列,然后你可以随意玩对象(排序,弹出,插入等)。


0
投票

与已经提到的其他用户一样,您可以将sort与lambda函数结合使用,以按元组的第二个元素进行排序。为了避免通过制表符拆分文本文件并替换所有换行符我建议使用csv阅读器:

import csv
def sort_films(file_name, destination_file):
    movie_list = []
    with open(file_name, 'r') as csvfile:
        # open csv file with delimiter '\t'  to avoid splitting your string
        csv_reader = csv.reader(csvfile, delimiter='\t')
        for row in csv_reader:
            movie_list.append((row[0], int(row[1]))) # cast string to int, so it gets sorted correctly

    # sort your list by the second element of your tuple by using labda function
    movie_list_sorted = sorted(movie_list, key=lambda x: x[1], reverse=True)

    # save your sorted list into the destination_file
    with open(destination_file,'w') as f:
        for row in movie_list_sorted:
            # while saving you can use an other format by replacing \t with whatever you want
            f.write('%s\t%s\n' % (row[0], row[1]))

    sort_films('top500.txt', 'sorted.txt')
© www.soinside.com 2019 - 2024. All rights reserved.