【问题标题】:Python Read txt file from highest to lowest scorePython从最高分到最低分读取txt文件
【发布时间】:2019-12-01 19:47:39
【问题描述】:

这里是初学者,我目前正在做一个练习,我必须让 Python 读取一个包含国家和分数的文本文件,然后我需要先打印最高分数,直到最低分数。 例如,一个文本文件可能如下所示: Canada 14 Brazil 9 South Korea 16 (还有很多其他不同分数的附加文本文件,但我从第一个开始) 到目前为止我的代码:

firstscoredocument = f.readlines()
for line in firstscoredocument:
    nums_str = line.split()[1:]
    nums = [int(n) for n in nums_str]
    max_in_line = max(nums)
    print max_in_line

此代码打印 14 9 16 我需要它来打印 South Korea 16 Canada 14 Brazil 9 另外,我似乎无法找到如何从最高到最低打印它们的方法...... 任何人都可以给我一个提示吗? 非常感谢:)

【问题讨论】:

  • 你应该使用 Python 3(你会写 print(max_in_line)),下个月 Python 2 将是 end-of-life'd

标签: python text


【解决方案1】:

对不起!但不要使用堆栈溢出来完成你的作业问题。这将影响您在论坛中的reputation

这里Pandas 将帮助您,假设您使用的是tab delimited file

from __future__ import print_function
import pandas as pd
data = pd.read_csv("sample_file.txt",sep='\t',header=None)
sort_by_life = data.sort_values(by=data.columns[1],ascending=False)
sort_by_life.to_csv("sort_by_life.txt", sep='\t', index=False, header=None)
print(sort_by_life)

输出:

South Korea 16
Canada  14
Brazil  9

尝试使用 Python 3,因为 python 2.x will be end of life.

希望对你有所帮助。

【讨论】:

    【解决方案2】:

    将文件读入字典然后sort the dictionary by values 并打印出来:

    with open("filename.txt") as f:
        countries_to_scores = {}
        for line in f:
            country, score = line.strip().split()
            countries_to_scores[country] = score
    
    for country in sorted(countries_to_scores, key=countries_to_scores.get):
        print(country, counties_to_scores[country])
    

    【讨论】:

      【解决方案3】:
      import os
      
      with open(r'yourtextfile.txt', 'r') as f:
          firstscoredocument = [x.replace('\n', '') for x in f.readlines() if x != '\n']
          country_and_scores = []
          for line in firstscoredocument:
              if line == os.linesep:
                  continue
              c, s = line.rsplit(' ', 1)
              country_and_scores.append([c, int(s)])
      
          country_and_scores.sort(key=lambda x: x[1], reverse=True) 
          for country_score in country_and_scores:
              print(*country_score )
      

      【讨论】:

      • 没有必要使用readlines 并检查os.linesep,您可以先使用for line in f,然后再使用if not line.strip(): continue。 Python 在所有操作系统上自动将换行符转换为\n
      【解决方案4】:

      我建议您将值读入字典,然后按值排序。如果您设法在下面的示例中创建字典 x,那么您将能够对其进行排序和打印。

      import operator
      x = {"South Korea": 16, "Brazil": 9, "Canada": 14}
      sorted_x = sorted(x.items(), key=operator.itemgetter(1), reverse=True)
      print(sorted_x)
      [('South Korea', 16), ('Canada', 14), ('Brazil', 9)]
      

      【讨论】:

      • 如果他能够从输入文件中制作字典 {"country": score} 就可以了。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-08
      • 1970-01-01
      • 2019-05-03
      • 1970-01-01
      • 1970-01-01
      • 2021-01-18
      相关资源
      最近更新 更多