python - 为什么我不断收到错误 "min() arg is an empty sequence"?

标签 python max min

我有以下代码:

test_file = open("test.txt","r")
numbers = test_file.readlines()
numbers = map(int,numbers)
print("Maximum number in list:", max(numbers))
print("Minimum number in list:", min(numbers))
test_file.close()

你能帮帮我吗,因为我一直收到错误信息:min() arg is an empty sequence。 (我在文件中写入了数字 15、30、4、9、41、76、32,它们在不同的行中)。

我得到这个输出:

Maximum number in list: 76
Traceback (most recent call last):
  File "\\student-server\users$\16fvarela\Documents\YEAR 
9\CS\Notes\PYTHON\test.py", line 5, in <module>
    print("Minimum number in list:", min(numbers))
ValueError: min() arg is an empty sequence

最佳答案

你的号码

numbers = map(int,numbers)

是一个迭代器(在 python 3 中;在 python 2 中,你会得到一个列表,一切都会按预期工作);当您应用 max(numbers) 时,您会耗尽迭代器; min 不再需要迭代(即 min 将提示空序列)。

如果您的数字列表足够短,您可以通过以下方式修复它

numbers = tuple(map(int,numbers))

关于python - 为什么我不断收到错误 "min() arg is an empty sequence"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57091056/

相关文章:

javascript - 如何使用 1 个文本框在空数组中添加 5 个数字?

algorithm - 找出多向图中平行边的最大数量

sql - 如何获取sql server中的最大长度值

sql - 雪花-sql : case when min vs first_value windows function

python - Python 中的最小或最大赋值运算符

python - 如何检查文件是否不是Python中的符号链接(symbolic link)

python - 使用 pandas 格式化数据以进行生存分析

python - 根据我的 df 中 ID 的进入和退出时间确定组大小

javascript - JS : find lowest/highest number from array within a specific range

python - 高效的字符串转十六进制函数