我有元組串列
sortedlist = [('hello', 41), ('hi', 16), ('bye', 4)]
我想寫入一個 .txt 檔案,以便每個元組中的單詞和整數位于由制表符分隔的同一行上。IE
hello 41
hi 16
bye 4
我知道如何寫入檔案即
with open("output/test.txt", "w") as out_file:
for item in sorted list:
out_file.write("Hello, world!" "\n")
但我正在努力弄清楚如何通過我的串列創建一個回圈來給我正確的輸出。
我試過了:
with open("output/test.txt", "w") as out_file:
for i in sortedlist:
out_file.write((str(sortedlist[i](0))) str(sortedlist[i](1)))
但我得到:
TypeError: list indices must be integers or slices, not tuple
我應該怎么做?
uj5u.com熱心網友回復:
在i實際的回圈是在串列中,如值('hello', 41)(嘗試print(i)回圈里面看到)。
這意味著您實際上是sortedlist[('hello', 41)]在回圈內部進行操作 - 嘗試將tuple用作您的 的索引list,這解釋了您遇到的例外。
由于i已經具有您想要的值,您可以使用它來訪問串列中的專案:
with open("output/test.txt", "w") as out_file:
for i in sortedlist:
out_file.write(str(i[0]) str(i[1]))
如果您想i成為串列的索引,可以使用for i in range(len(sortedlist)):,但如果您只是按順序訪問串列的成員,則不應這樣做。另見enumerate。
最后,您可以使用序列解包使解決方案更加簡潔:
with open("output/test.txt", "w") as out_file:
for a, b in sortedlist:
out_file.write(f"{a}\t{b}\n")
理想情況下a,您應該給出b適當的名稱。我還修改了它以插入示例中的制表符和換行符,并使用f 字串將其格式化為字串。
uj5u.com熱心網友回復:
您撰寫了不正確的代碼,這就是您收到錯誤的原因。這里的 for 回圈中的 i 不是索引,而是您正在迭代的串列元素。因此,要遍歷索引,您需要使用 range(len(sortedlist))。為了獲得有利的輸出,您應該將代碼修改為:
with open("test.txt", "w") as out_file:
for i in range(len(sortedlist)):
out_file.write((str(sortedlist[i][0])) '\t' str(sortedlist[i][1]) '\n')
這樣你的輸出將是:
hello 41
hi 16
bye 4
uj5u.com熱心網友回復:
with open("output/test.txt", "w") as out_file:
for i in sortedlist:
out_file.write((str(sortedlist[i](0))) str(sortedlist[i](1)))
在上面的代碼中,您使用 'i' 作為 'sortedlist' 的索引,但這里的 'i' 用于迭代元組,因此
sortedlist[i] implies sortedlist[("hello", 41)] which gives you the error!
要修復它,您可以在 forloop 中迭代一個范圍或洗掉 .write() 函式中的 [i] 。以下是應該適合您的代碼:
with open("output/test.txt", "w") as out_file:
for i in sortedlist:
out_file.writeline(' '.join(map(str, i)))
writeline() 函式會自動在字串末尾添加換行符。
' '.join(iterable) 將使用在它之前的字串中指定的分隔符連接可迭代元素。我沒有指定一個因此它使用空間。
map 函式將第二個引數的每個元素映射到作為第一個引數提供的函式中。然后將該函式的輸出附加到一個可迭代物件,從而產生新的元素可迭代物件,這些元素是第二個 arg 元素的函式。
map(func, iterable)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/376196.html
