Python 3:txt文件中最大的数字

时间:2018-09-18 17:01:58

标签: python-3.x max

那是我的代码:

def get_latest(file_name):
    max = 0
    with open(file_name) as file:
        for line in file.readlines():            
            num = int(line.split("\t")[2])
            if (max < num):
                max = num
            line=line.split("\t")
            #y=max
            if str(max) in line:
                print(line)

get_latest('game_stat.txt')

输出:

['Minecraft', '23', '2009', 'Survival game', 'Microsoft\n']
['Terraria', '12', '2011', 'Action-adventure', 'Re-Logic\n']
['Diablo III', '12', '2012', 'RPG', 'Blizzard Entertainment\n']

我应该怎么做才能只打印最新发布日期的行?

Txt文件如下:

Minecraft   23  2009    Survival game   Microsoft
World of Warcraft   14  2004    RPG Blizzard Entertainment
Terraria    12  2011    Action-adventure    Re-Logic
Diablo III  12  2012    RPG Blizzard Entertainment
Half-Life 2 12  2004    First-person shooter    Valve Corporation
Counter-Strike  12.5    1999    First-person shooter    Valve Corporation
The Sims    11.24   2000    Simulation  Electronic Arts
StarCraft   11  1998    Real-time strategy  Blizzard Entertainment
Garry's Mod 10  2006    Sandbox Facepunch Studios
....etc

我不知道。预先感谢!

1 个答案:

答案 0 :(得分:1)

您需要对所有行执行max,并使用key function将年份作为整数进行比较。下面,我使用csv.reader为我解析文件的结构。

import csv

def get_latest(file_name):
    with open(file_name, newline='') as file:
        reader = csv.reader(file, dialect='excel-tab')
        return max(reader, key=lambda row: int(row[2]))

print(get_latest('game_stat.txt'))

年份最大的条目将是最新发布的条目。 (假设您没有将来发布的游戏数据。)