簡體   English   中英

將整數列表更改為文件的字符串

[英]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()

是否要以保存輸入的方式保存輸出? 在這種情況下,您可以輕松地將printfile參數一起使用。

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM