Python从最高到最低读取txt文件

2024-10-01 15:37:07 发布

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

完全初学者在这里,我目前正在做一个练习,我必须让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 而且,我似乎找不到一个方法如何从最高到最低打印它们。。。 谁能给我一个提示吗? 非常感谢:)


Tags: 代码inforline分数max文本文件brazil
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 )

很抱歉这么说!!!但是不要用堆栈溢出来完成你的家庭作业问题。这会影响你在论坛上的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

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

希望这对你有帮助。你知道吗

将文件读入字典,然后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])

相关问题 更多 >

    热门问题