0

我最近开始使用 python,我想知道如何在不使用数组/列表的情况下使我的程序具有相同的输出。基本上,它会打开一个包含数字的文件,然后打印最大的数字以及文件中的数字数量。我想知道如何将我的程序转换成不使用数组/列表格式的东西。

def main():
    infile = open('numbers.dat', 'r')

    numbers = []
    for line in infile:
        numbers.append(int(line))
    infile.close()

    largest = max(numbers)
    print('The largest number in the file is: ',largest)

    count = len(numbers)
    print('The amount of numbers in the file is: ', count)
main()
4

2 回答 2

1
def main():
    with open('numbers.dat') as infile:
        largest_num = float('-inf') # in case all your numbers are negative,
                                    # 0 can't be default
        for i, line in enumerate(infile, 1): # i is the line number
            largest_num = max(largest_num, int(line))
        print 'Largest num is: ', largest_num
        print 'num of lines is: ', i

main()
于 2013-04-01T02:09:47.277 回答
0

在这种情况下没有理由不使用数组,但如果你真的想不使用数组,你可以这样做。

def main():
    infile = open('numbers.dat', 'r')

    largest = 0
    count = 0
    for line in infile:
        number = int(line)

        if number > largest:
            # If the number on the line we are currently reading is greater than,
            # our previously highest. Set the highest to this number instead.
            largest = number

        # Increment the number of lines we have read.
        count += 1

    infile.close()

    # Finally print the values we got from parsing the file
    print('The largest number in the file is: %s' % largest)
    print('The amount of numbers in the file is: %s' % count)
main()
于 2013-04-01T01:28:02.230 回答