我有一個串列,如下所示:
alist = [['Hi', 500], ['Bye', 500.0, 100, 900, 600], ['Great', 456, 700.0, 600], ["Yay", 200, 350.0], ["Ok", 200, 300, 400.0]]
我想將此串列寫入 .txt 檔案,使文本檔案內容看起來像這樣,第一個字串后面有一個空格,其余的值用逗號分隔:
期望的輸出:
嗨 500
再見 500.0,100,900,600
偉大的 246,700.0,600
耶 200,350.0
好的 200,300,400.0
這是我迄今為止一直在嘗試的:
txtfile = open("filename.txt", "w")
for i in alist:
txtfile.write(i[0] " ")
j = 1
while j < len(i):
txtfile.write([i][j] ",")
txtfile.write("\n")
但是,我只是不斷收到IndexError("List Index out of range")錯誤訊息。
有沒有辦法在不匯入任何模塊的情況下解決這個問題?
提前致謝 :)
uj5u.com熱心網友回復:
其他方法。
alist = [['Hi', 500], ['Bye', 500.0, 100, 900, 600], ['Great', 456, 700.0, 600], ["Yay", 200, 350.0], ["Ok", 200, 300, 400.0]]
fn = "filename.txt"
mode = "w"
with open(fn, mode) as h: # file handle is auto-close
for v in alist:
h.write(v[0] " ")
j = 1
while j < len(v):
if len(v) - 1 == j:
h.write(str(v[j])) # don't write a comma if this is the last item in the list
else:
h.write(str(v[j]) ",")
j = 1 # increment j to visit each item in the list
h.write("\n")
輸出
Hi 500
Bye 500.0,100,900,600
Great 456,700.0,600
Yay 200,350.0
Ok 200,300,400.0
uj5u.com熱心網友回復:
這快速、簡單并且無需任何匯入即可作業:
str(alist).replace('],', '\n').replace('[', '').replace(']', '').replace("'", '')
給你:
Hi, 500
Bye, 500.0, 100, 900, 600
Great, 456, 700.0, 600
Yay, 200, 350.0
Ok, 200, 300, 400.0
您可以將其寫入磁盤:
alist = str(alist).replace('],', '\n').replace('[', '').replace(']', '').replace("'", '')
with open('filename.txt', 'w') as f:
f.write(alist)
uj5u.com熱心網友回復:
也許你可以試試這個代碼:
使用list()、map()和str.join()
alist = [['Hi', 500], ['Bye', 500.0, 100, 900, 600], ['Great', 456, 700.0, 600], ["Yay", 200, 350.0], ["Ok", 200, 300, 400.0]]
t = open("a.txt", "w")
for i in alist:
t.writelines(i[0] " " ",".join(list(map(str, i[1:]))) "\n")
# if you want to do it without map()
# you can use list comprehension
# ","join([str(j) for j in i[1:])
和輸出檔案
Hi 500
Bye 500.0,100,900,600
Great 456,700.0,600
Yay 200,350.0
Ok 200,300,400.0
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/347563.html
標籤:Python
