[英]Changing a list of integers to a string for a file
我有一個整數列表,我需要對其進行排序並顯示在屏幕上(我記下來了),但我還需要將其寫入一個新文件中。
data = []
with open('integers.txt','r') as myfile:
for line in myfile:
data.extend(map(int, line.split(',')))
print (sorted (data))
text_file = open('sorted_integers.txt', 'w')
text_file.write(sorted(data))
text_file.close()
是否要以保存輸入的方式保存輸出? 在這種情況下,您可以輕松地將print
與file
參數一起使用。
with open('sorted_integers.txt', 'w') as f:
print(*sorted(data), sep=',', end='', file=f)
始終建議您在處理文件I / O時使用with...as
上下文管理器,這樣可以簡化代碼。
如果您使用的是python2.x, __future__
執行__future__
導入:
from __future__ import print_function
另一點(感謝PM 2Ring)是,調用list.sort
實際上比sorted
更具性能/效率,因為原始列表是在原地排序的 ,而不是像sorted
那樣返回新的列表對象。
綜上所述,
data.sort() # do not assign the result!
with open('sorted_integers.txt', 'w') as f:
print(*data, sep=',', end='', file=f)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.