python - 如何打印按点数排序? Python

标签 python python-3.x

结果.txt

Alan: 15 points.
Smith: 10 points.
Luka: 20 points.

预期打印:

Luka: 20 points.
Alan: 15 points.
Smith: 10 points.

代码:

def print_results():

    with open("results.txt", "r") as f:
        linija=f.readlines()

    linija=sorted(linija,key=itemgetter(1),reverse=True)

    print("######### HALL OF FAME #########\n")
    for line in linija:
        print line
    print("################################")

需要帮助,如何获取这些点并按它们排序?

最佳答案

您可以在阅读时拆分每一行,然后按结果列表中的 int 值进行排序。然后,使用 ' '.join 打印输出,将其作为字符串返回

with open("results.txt", "r") as f:
    linija=[i.split() for i in f.readlines()]

linija = sorted(linija,key=lambda x: int(x[1]),reverse=True)

print("######### HALL OF FAME #########\n")
for line in linija:
    print(' '.join(line))
print("################################")

输出:

######### HALL OF FAME #########

Luka: 20 points.
Alan: 15 points.
Smith: 10 points.
################################

关于python - 如何打印按点数排序? Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53603870/

相关文章:

python - PhantomJS + Selenium Webdriver + Python 程序执行异常

python - QPython无法安装requests模块

python - 在 Windows 10 中安装适用于 Python 3.7.1 的 Mayavi

python - 使用 QT 运行 pytest 时出现致命的 Python 错误

python - 从外部获取正在运行的 Python 脚本的源代码

python - 包括列表理解中的第一个和最后一个元素

python - 连接同一数据框中的行

python - 我尝试在 python 上安装 httplib 但出现错误

python - 处理 python 请求中的井号 (#)

python-3.x - 递归遍历嵌套字典并返回第一个匹配键的值