[英]find the smallest number in a text file (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,哈哈)
編輯:我在最小的 = 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])
我沒有運行代碼,但它應該可以工作。 如果您有更多的錯誤檢查,那將是最好的。 例如,如果line
不是數字, int(line)
可能會引發異常。
您的代碼不起作用,因為列表推導式應該使用方括號而不是大括號。
它應該是[int(line) for line in fread]
而不是{int(line) for line in fread}
一旦你有一個列表,函數min
也將起作用。
max=-9999
for line in open('lines.txt').readlines():
#print(line)
for word in line.split():
#print(word,word.isnumeric())
if word.isnumeric() and int(word)>max:
max=int(word)
print(max)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.