查找文件中的最大值并打印出名称的值

问题描述 投票:0回答:2

我需要创建一个程序来打开一个文件,然后读取文件内的值,然后打印出具有最大值的名称。

该文件包含以下信息:

Juan,27
Joe,16 
Mike,29
Roy,10

现在我的代码如下:

UserFile = input('enter file name')
FileOpen = open(User File,'r')
for lines in User File:
    data = line.split(",")
    name = data[0]
    hrs = data[1]
    hrs = int(hrs)
    LHRS = 0
    if hrs > LHRS:
    LHRS = hrs
    if LHRS == LHRS:
        print('Person with largest hours is',name)

打印出以下内容:

Person with the largest hours is Juan
Person with the largest hours is Mike

我怎样才能让它只打印出真正最大的?

python text-files return-value filereader
2个回答
2
投票

虽然您的第一次尝试的努力相当令人印象深刻,但您在这里无法做的是.. 跟踪名称,同时跟踪最大值!我确信可以按照你的方式完成,但我可以建议替代方案吗?

import operator

让我们像我一样读取文件。这是很好的做法,此方法可以处理文件关闭,如果处理不当,可能会导致许多问题。

with open('/Users/abhishekbabuji/Desktop/example.txt', 'r') as fh:
    lines = fh.readlines()

现在我的列表中的每一行都称为

lines
,其中还包含这个烦人的
\n
。让我们用空白替换它
''

lines = [line.replace("\n", "") for line in lines]

现在我们有一个这样的列表。

['Name1, Value1', 'Name2, Value2'..]
我现在打算做的是,对于列表中的每个字符串项,将第一部分作为键,将第二部分的整数部分作为我的字典的值,称为
example_dict
。因此,在
'Name1, Value1'
中,
Name1
是索引
0
中的项目,而
Name2
是索引
1
中的项目,当我将其转换为列表时,就像我在下面所做的那样,并将键、值对添加到词典。

example_dict = {}
for text in lines:
    example_dict[text.split(",")[0]] = int(text.split(",")[1])
print(example_dict)

给予:

{'Juan': 27, 'Joe': 16, 'Mike': 29, 'Roy': 10}

现在,获取值为 max 的键并打印它。

largest_hour = max(example_dict.items(), key=operator.itemgetter(1))[1]

highest_key = []
for person, hours in example_dict.items():
    if hours == largest_hour:
        highest_key.append((person, hours))

for pair in highest_key:

    print('Person with largest hours is:', pair[0])    

0
投票

我正在研究 html 和 css 但有一家公司来参观

© www.soinside.com 2019 - 2024. All rights reserved.