python - 在文本文件中找到最小的数字(python)
问题描述
所以我有一个大约 400 行的文本文件,每行都有一个数字,我需要找到这些数字中最小的一个。
我目前有
def smallestnumber(fread, fwrite):
number = {int(line) for line in fread}
smallest = min(number)
print ("smallest number is", smallest)
但由于某种原因它不起作用。在 .txt 文件中获得最小数字的最佳方法是什么?(fread 是我在 main() 函数中打开的 .txt 文件!我会将数字写入 fwrite,一旦我设法弄清楚了,哈哈)
编辑:我在 minimum = min(number) 部分得到一个错误 (ValueError),说“min() arg 是一个空序列”。
EDIT2:我使用 test.txt 文件首先测试代码,它只是
1000 700 450 200 100 10 1 每个在不同的行上 所以与我应该使用的文件的格式/类型相同
fread(我得到数字的地方)和 fwrite(我想保存数字的地方)在 main() 中定义如下
name= input("Give the name of the file which to take data from: ")
fread = open(name, "r") #File which is being read
name2= input("Give the name of the file where to save to: ")
fwrite = open(name2, "w") #File which is being typed to
我很抱歉这个问题可能不好的“格式化”等,我是 python 和 StackOverflow 的新手!
谢谢您的帮助!
解决方案
def smallestnumber(fread, fwrite):
# store the numbers in a list
numbers = [int(line) for line in fread]
# sort the list so that the smallest number is the first element of the list
numbers.sort()
# print the first element of the list which contains the smallest number
print ("smallest number is: {0}".format(numbers[0])
我没有运行代码,但它应该可以工作。如果您有更多的错误检查,那将是最好的。例如,如果不是数字,int(line)
可能会引发异常。line
您的代码不起作用,因为列表推导应该使用方括号而不是大括号。
它应该是[int(line) for line in fread]
而不是{int(line) for line in fread}
一旦你有一个列表,该功能min
也将起作用。
推荐阅读
- python - 除非通过 CMD 输入,否则无法从 python 控制台导入模块
- android - 由于 sym_keyboard_feedback_delete.png 文件,App Bundle 构建失败
- python - 如何在python中计算特征脸?
- angular - 从 css 文件中获取图标列表以在 Angular 6 组件中使用
- teamcity - TeamCity 和日历版本控制
- rust - Is storing data and a mutable pointer to that data in a struct safe?
- python - 为什么 Python wikipedia 包中的“sections”属性返回一个空列表?
- python - When should a single session instance be used for requests?
- java - call data from array by using identifier
- python - 使用 Python 请求时无法将 CSRF 令牌传递到表单中