python - 为什么 max 在 python 中是一个空序列

标签 python max

我是一个相当有经验的编码员,但我无法理解 python 中的这个问题。它引用的文本文件布局为

Jeff 4 7 7
Rich 2 1 9
Chris 4 6 5

然而,当我运行代码时,它计算出了前两组数据,但没有计算出最后一组。代码是:

with open(classno, 'r') as f: #it doesn't write last score and 
        for line in f:
            nums_str = line.split()[1:]
            nums = [int(n) for n in nums_str]
            max_in_line = max(nums) #uses last score of it need to combine
            print (max_in_line)
            with open('class11.txt', 'r') as f:
                parts = line.split()
                if len(parts) > 2:
                    name = str(parts[0])
                    f = open(classno, 'a')
                    f.write(("\n") + (name) + (" ") + str(max_in_line))

        f.close()

...但是在文本文件的最后一行它说:

max() arg is an empty sequence

最佳答案

您的文件末尾可能有一个换行符,因此您正在阅读一个空行。试试这个:

for line in f:
    if line: 
        ....

关于python - 为什么 max 在 python 中是一个空序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28031754/

相关文章:

python - 可视化交锋记录的最佳方式是什么?

python - Vercel:无法使用 Python Serverless API 导入其他函数

MySQL - 在where子句中引用聚合列

python - HomeAssistant 取消 AppDaemon 中的回调

python - 将 matplotlib 绘图轴设置为数据框列名称

Java:查找数组中的最大值

Python - 从数组中获取最频繁的元素/将 numpy 数组转换为 std 数组

python - 最大化函数 : what method?

python - 将列表列表转换为Python中的字典字典

matlab - 如何使用 max 或 min 返回的多维索引?