我仍然是一個python初學者。我需要將 2 個串列寫入兩個不同的文本檔案,然后對每個文本檔案進行排序,最后將這兩個文本檔案輸出添加到一個也已排序的新文本檔案中。我需要按升序排序。當我這樣做時,我嘗試將數字轉換為 str 程式可以列印未排序的串列,但是當我添加 sort 時問題出現了。希望這是有道理的。
number1 = [5000, 300, 4, 1, 2]
number2 = [19, 66, 8, 17, 100]
with open("numbers1.txt", "w") as file1:
file1.write(str(number1))
with open("numbers2.txt", "w") as file2:
file2.write(str(number2))
with open("numbers1.txt", "r ") as file1:
content = file1.read()
content.sort()
print(content)
with open("numbers2.txt", "r ") as file2:
content2 = file2.read()
content2.sort()
print(content2)
#combined = file1 file2
#combined.sort()
#print(combined)
然后程式給了我這個錯誤
content.sort()
AttributeError: 'str' object has no attribute 'sort'
我還沒有將最后兩個排序串列寫入一個新的文本檔案,該檔案也已排序
uj5u.com熱心網友回復:
file.read()回傳一個字串,而不是一個串列。如果需要串列,則需要將其轉換回串列,但首先將串列保存到檔案的格式并不是最好的,因為它會創建額外的字符。
將串列的一個元素寫入檔案的每一行可能是一個更好的主意。然后,讀取檔案
with open("numbers1.txt", "w") as file1:
file1.writelines(str(n) for n in number1)
with open("numbers1.txt", "r ") as file1:
content = []
for line in file1:
content.append(int(line))
content.sort()
您可以用理解替換讀取回圈:
with open("numbers1.txt", "r ") as file1:
content = [int(line) for line in file1]
content.sort()
如果這是一個選項,您可以寫入json檔案而不是常規文本檔案。該json包取讀串列轉換為正確的格式,當您使用的護理json.load()。
import json
with open("numbers1.json", "w") as file1:
json.dump(numbers1, file1)
with open("numbers1.txt", "r ") as file1:
content = json.load(file1)
content.sort()
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/375909.html
