【发布时间】:2022-01-10 20:41:16
【问题描述】:
我有元组列表
sortedlist = [('hello', 41), ('hi', 16), ('bye', 4)]
我想将其写入 .txt 文件,以便每个元组中的单词和整数位于由制表符分隔的同一行上。 即
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
我应该怎么做?
【问题讨论】: