在fi中寻找最大值

2024-04-25 21:36:00 发布

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

我在上一年级的计算机科学课,正在学习Python,所以请耐心听我说。任务是使用Python打开一个文件,读取它,并在该文件中找到最大值,而不使用任何内置函数或我们在课堂上没有讨论过的概念。我可以读取文件并获取值,但我的问题是,我的代码会将值“30”改为“3”,并将值“0”改为“30”。到目前为止,我的情况是:

def maxValueInFile(fileName):
    inputFile = open(fileName, "r")
    currentMax = int(0)
    for value in inputFile.read():
        if value.isdigit():
            value = int(value)
            if value > currentMax:
                currentMax = value
    inputFile.close()
    return currentMax

当我运行文件时,它不会返回大于9的数字,可能是因为


Tags: 文件函数代码概念ifvaluedef情况
3条回答

您试图在这段代码中做太多的工作(我将对此进行注释,以便您可以看到哪里出错):

# inputFile.read() returns something like "30\n40\n50"
for value in inputFile.read():  
    # now value is something like "3" or "0"   
    if value.isdigit():
        value = int(value)
        # and now it's 3 or 0

将字符串拆分为数字没有好处,所以不要这样做。:)

currentMax = 0
for line in inputFile.readLine():
    value = int(line)
    if value > currentMax:
        currentMax = value

请注意,如果line不能转换为int,则此代码将引发ValueError异常!你知道吗

几个样式注释(我已经应用于上面的代码):

  • 你不需要说int(0),因为0已经是一个int了。你知道吗
  • 在转换类型时,最好将一个新变量赋给新类型(当您开始使用静态类型检查时,这是必需的,因此这是一个好习惯)。在上面的代码中,我调用了从文件line中读取的文本行,以帮助我记住它是一行文本(即a str),然后我将数值命名为value,以帮助我记住这是我可以在比较中使用的实际数字(即int)。你知道吗

如果要逐位读取,可以通过将临时结果连续乘以10,然后将读取的最后一个数字的值相加来建立实数。你知道吗

def maxValueInFile(fileName):
    inputFile = open(fileName, "r")
    currentMax = int(0)
    number = 0
    for value in inputFile.read():
        if value.isdigit():  # again found a digit
            number = number * 10 + int(value)
        else:   # found a non-digit
            if number > currentMax:
                currentMax = number
            number = 0
    if number > currentMax:  # in case the for-loop ended with a digit, the last number still needs to be tested
        currentMax = number
    inputFile.close()
    return currentMax

inputFile.read()返回一个字符串,当您对其进行迭代时,该字符串将被分解为多个字符。假设输入文件的每一个值都在一行中,那么您需要inputFile.read().splitlines()。你知道吗


不过,下面是我的写作方法,并附上注释:

def maxValueInFile(fileName):
    currentMax = 0
    with open(fileName) as inputFile:  # Avoid manually opening and closing files
        for line in inputFile:  # Avoid reading the whole file
            # If we can assume the file only contains numbers,
            # we can skip the ".isdigit" check.
            value = int(line)  # "int()" doesn't care about whitespace (newline)
            if value > currentMax:
                currentMax = value
    return currentMax

相关问题 更多 >