我需要能夠讓 python 創建一個新的文本檔案,以某種方式顯示串列,但我不確定如何在文本創建區域中使用格式
def write_to_file(filename, character_list):
### Using a while loop to iterate over the list of lists (characters).
index = 0
while index < len(character_list):
with open("new_characters.txt", "w") as output:
output.write(str(character_list))
index = index 1
上面的代碼是我為了在文本檔案中顯示完整串列而制作的代碼,但它只是將所有內容放在一行中。
我需要像這樣設定它:
神奇女俠
戴安娜·普林斯
小時 5 5 0 0 90
蝙蝠俠
布魯斯·韋恩
小時 6 2 0 4 80
代替:
[['Wonder Woman', 'Diana Prince', 'h', 5, 5, 0, 0, 90], ['Batman', 'Bruce Wayne', 'h', 6, 2, 0, 4, 80],
這是上面發布的代碼的輸出。
而且代碼一定是回圈的!
uj5u.com熱心網友回復:
嘗試這個。
def write_to_file(filename, character_list):
### Using a while loop to iterate over the list of lists (characters).
index = 0
while index < len(character_list):
with open("new_characters.txt", "w") as output:
for item in character_list:
for character in item:
output.write(str(character) '\n')
index = index 1
uj5u.com熱心網友回復:
這適用于您以您要求的格式顯示的子集。
def write_to_file(filename, character_list):
# open file with given filename, in 'write' mode
with open(filename, 'w') as f:
# iterate over characters in for loop
# using tuple unpacking
for (hero_name, char_name, *data) in character_list:
# write hero and character names on a line each
f.write(hero_name '\n') # e.g. 'Wonder Woman'
f.write(char_name '\n') # e.g. 'Diana Prince'
# convert all remaining elements to a string
# using list comprehension
data = [str(i) for i in data]
# create a single string from a list of values separated by a space
# using string join method on the list
data = ' '.join(data)
# write to file with newline
f.write(data '\n') # e.g. 'h 5 5 0 0 90'
其關鍵組件是元組解包、串列推導和字串連接方法。我還包括在打開檔案時實際使用的檔案名引數的使用。這意味著如果您還沒有將帶有擴展名的檔案名傳遞給函式呼叫。
uj5u.com熱心網友回復:
試試這個方法:-
- For 回圈將是一個更好的選擇
- 使用
\n新線
def write_to_file(filename, character_list):
with open(f"{filename}.txt", "w") as output:
for characters in character_list:
for character in characters:
character =str(character)
output.write(character ("\n" if len(character)>1 else "" ))
#output.write(character ("\n" if len(character)>1 else " " )) for --> h 5 5 0 0 9 0
write_to_file('Any',[['Wonder Woman', 'Diana Prince', 'h', 5, 5, 0, 0, 90], ['Batman', 'Bruce Wayne', 'h', 6, 2, 0, 4, 80]])
輸出:
Wonder Woman
Diana Prince
h550090
Batman
Bruce Wayne
h620480
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/347412.html
下一篇:如何修復此功能的輸出?
