【问题标题】:(Python) Sorting movie by sales using file input and output(Python) 使用文件输入和输出按销售额对电影进行排序
【发布时间】:2019-03-11 14:46:43
【问题描述】:

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

所以在一个文本文件中有一个随机顺序排列的前 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")

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

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

【问题讨论】:

  • 使用dict,比如ratings = {}; ratings['foo'] = 1234; 然后最后sorted(ratings.items(), key=lambda x: x[1]) 应该这样做:)

标签: python python-3.x file io


【解决方案1】:

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

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

应该这样做

【讨论】:

    【解决方案2】:

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

    如下所示: Sort tuples based on second parameter

    【讨论】:

      【解决方案3】:

      我建议你上课。在您的情况下,您需要一个带有一个字符串和一个整数的类。从那时起,一切都会变得更容易。您将只有一个充满对象的数组,然后您可以随意使用对象(对它们进行排序、弹出、插入等)。

      【讨论】:

        【解决方案4】:

        就像其他用户已经提到的那样,您可以将 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')
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2017-09-30
          • 1970-01-01
          • 2010-11-24
          • 2021-12-31
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多