簡體   English   中英

將嵌套列表中的整數輸出到文本文件中的字符串

[英]Outputting integers in a nested list to string in a text file

所以我目前在我的程序末尾有這個代碼,允許用戶保存文本文件。 我不知道如何將數據轉換為字符串,如果我嘗試使用此代碼,這就是給我錯誤的原因。

save = input("Would you like to save the latest generation? ('y' to save):")
if save == 'y':
    destination = input("enter destination file name:")
    with open(destination, 'w') as file:
        file.writelines('\t'.join(i) + '\n' for i in original_graph)
else:
    print("End of program.")

但是,我的original_graph是一個只有整數值的嵌套列表,例如: [0,1,1,0],[0,0,0,1],[0,0,1,0]

我如何才能使文本文件看起來像

0110 0001 0010

保存后在文本文件中? 另外,有沒有辦法提示用戶是否覆蓋了現有文件?

感謝您的時間。

編寫此內容的一種緊湊方法是使用列表推導式。 為方便起見,我將使用stdout作為輸出文件。

import sys

original_graph = [
    [0, 1, 1, 0],
    [0, 0, 0, 1],
    [0, 0, 1, 0],
]

f = sys.stdout
rows = [''.join([str(u) for u in row]) for row in original_graph]
f.write('\n'.join(rows) + '\n')

輸出

0110
0001
0010

要將數據保存到名稱為存儲在destination的字符串的文件中,只需執行以下操作:

rows = [''.join([str(u) for u in row]) for row in original_graph]
with open(destination, 'w') as f:
    f.write('\n'.join(rows) + '\n')

要檢查文件是否已經存在,請使用os.path.exists函數。 如果您需要這方面的進一步幫助,請提出一個新問題。 Stack Overflow 問題應該包含一個問題,以便最大限度地為未來的讀者提供有用的信息。

請檢查這個作品

original_graph=[[0,1,1,0],[0,0,0,1],[0,0,1,0]]
save = input("Would you like to save the latest generation? ('y' to save):")
if save == 'y':
    destination = input("enter destination file name:")
    with open(destination, 'w') as file:
        file.writelines('\t'.join(str(i) for i in original_graph))
else:
    print("End of program.")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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