python-3.x - Python 3: largest number in txt file
问题描述
Thats my code:
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')
That's output:
['Minecraft', '23', '2009', 'Survival game', 'Microsoft\n']
['Terraria', '12', '2011', 'Action-adventure', 'Re-Logic\n']
['Diablo III', '12', '2012', 'RPG', 'Blizzard Entertainment\n']
What should I do to print only line with newest released date?
Txt file looks like this:
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
I can't figure it out. Thanks in advance!
解决方案
您需要使用将年份作为整数进行比较的关键函数max
来处理所有行。下面,我用来为我解析文件的结构。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'))
年份最大的条目将是最近发布的条目。(假设您没有未来游戏的数据。)
推荐阅读
- android - 如何在 Android Studio 中按名称搜索文件
- list - Java 中的 BlockingDeque 是什么?
- javascript - 通过 Link 将 Container 中的 props 和 fetch 传递给一个元素
- sql - pyodbc 似乎不处理来自 ORACLE DB 的 CASE 语句
- tensorflow.js - Typescript 和 Tensorflow.js 模型
- javascript - Ant Design:单击折叠标题时如何防止扩展,但允许按钮?
- django - 如何在 Django 中使用表单向导更新帖子
- postgresql - 如何将 PostgreSQL 9.6 中的数据库备份恢复到 PostgreSQL 12.2?
- c# - 如何访问 Outlook vsto 中的“收件人”自动填充电子邮件地址?缓存的联系人
- sql - T-SQL 存储过程错误:关键字“END”附近的语法不正确。严重性 15 PROCEDURE_1