与Python霍姆搏斗

2024-06-26 13:04:06 发布

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

我有一个.txt文件,里面有几行:

325255, Jan Jansen      
334343, Erik Materus   
235434, Ali Ahson  
645345, Eva Versteeg  
534545, Jan de Wilde  
345355, Henk de Vries 
  1. 写一个从打开文件开始的程序kaartnummers.txt文件你知道吗
  2. 确定文件中的行数和最大卡号。然后打印这些数据。你知道吗

我的代码还没完成,但我至少试过了!地址:

def kaartinfo():
    lst = []
    infile = open('kaartnummers.txt', 'r')
    content = infile.readlines()

    print(len(content))
    for i in content:
        print(i.split())
kaartinfo()

我知道我的程序会打开文件并计算其中的行数。。所有这些都是错误的<;3

我不知道怎么才能得到名单上的最大数字。。如果你有答案,请使用简单易读的Python语言。你知道吗


Tags: 文件程序txtdecontentaliinfilejan
2条回答

这应该足以完成这项工作:

with open('kaartnummers.txt', 'r') as f:

    data = f.readlines()

    print('There are %d lines in the file.' % len(data))
    print('Max value is %s.' % max(line.split(',')[0] for line in data))

给定您提供的输入文件,输出将是:

There are 6 lines in the file.

Max value is 645345.

当然,你可以把它放在函数里,如果你喜欢的话。你知道吗

我不擅长python,可能还有更优雅的解决方案,但我会这样做。有些人可能会说,这是Python中的C++ + java,很多人都倾向于避免这种情况。你知道吗

def kaartinfo():
    lst = []
    infile = open('kaartnummers.txt', 'r')
    content = infile.readlines()

    for i in content:
        value = i.split(',')
        value[0] = int(value[0])
        lst.append(value)

    return lst

使用kaartinfo()函数检索列表

my_list = kaartinfo()

假设第一个值是最大值

maximumValue = my_list[0][0]

检查列表中的每个值,检查它们是否大于当前最大值

# if they are, set them as the new current maximum
for ele in my_list:
    if ele[0] > maximumValue:
        maximumValue = ele[0]

当上述循环完成时,最大值将是列表中的最大值

#Convert the integer back to a string, and print the result
print(str(maximumValue) + ' is the maximum value in the file!')

相关问题 更多 >