![](/img/trans.png)
[英]How to take a list of tuples and change the tuples from strings to integers
[英]Write to file from list of tuples with strings and integers
我有元組列表
sortedlist = [('hello', 41), ('hi', 16), ('bye', 4)]
我想將其寫入 a.txt 文件,以便每個元組中的單詞和 integer 位於由制表符分隔的同一行上。 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")
但我正在努力弄清楚如何通過我的列表創建一個循環,該列表將為我提供正確的 output。
我試過了:
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
我應該怎么做呢?
循環中的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)):
,但如果您只是按順序訪問列表的成員,則不應這樣做。
最后,您可以使用序列解包來使解決方案更加整潔:
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-string將其格式化為字符串。
您編寫了不正確的代碼,這就是您收到錯誤的原因。 這里 i in for 循環不是索引,而是您正在迭代的列表的元素。 因此,要遍歷索引,您需要使用 range(len(sortedlist))。 要獲得您喜歡的 output,您應該將代碼修改為:
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')
這樣,您的 output 將是:
hello 41
hi 16
bye 4
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() function 中的 [i]。 以下是應該為您工作的代碼:
with open("output/test.txt", "w") as out_file:
for i in sortedlist:
out_file.writeline(' '.join(map(str, i)))
writeline() function 自動在字符串末尾附加一個換行符。
' '.join(iterable) 將使用在它之前的字符串中指定的分隔符連接可迭代元素。 我沒有指定一個,因此它使用空間。
map function 將第二個參數的每個元素映射到作為第一個參數提供的 function 中。 Then the output of that function is append to an iterable thus producing new iterable of elements which are a function of the elements of second arg.
map(func, iterable)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.