[英]Writing dictionary list values to a text file
我有以下字典,其中包含每个值的列表
dictionary = {
0 : [2, 5]
1 : [1, 4]
2 : [3]
}
我需要 output 像这样的文件中的值
2 5
1 4
3
在每一行的最后一位我需要有一个空格。
我已经尝试使用此代码
with open('test.txt', 'w') as f:
for value in dictionary.values():
f.write('{}\n'.format(value))
所以我想省略output的[]和。
我还尝试将字典的值保存到列表中,然后处理列表而不是字典。 但这不是我想的最明智的事情。 数字也以错误的顺序保存,括号和逗号也被保存。
a = list(dictionary.values())
for i in a:
with open('test.txt', 'w') as f:
for item in a:
f.write("%s\n" % item)
因为我得到了这个 output
[3, 2]
[5, 1]
[4]
你的第一个版本非常接近,所以让我们改进一下。
您可以做的是使用列表理解来遍历并将每个 integer 转换为字符串。 然后在结果字符串列表上调用join
。
像下面这样的东西应该可以工作:
dictionary = {
0: [2, 5],
1: [1, 4],
2: [3]
}
with open('test.txt', 'w') as f:
for value in dictionary.values():
print(' '.join([str(s) for s in value]), file=f)
旁注:我已将f.write
替换为print
,以避免手动指定换行符。
如果您希望每行尾随空格字符,您可以使用 f-strings 执行此操作:
print(f"{' '.join([str(s) for s in value])} ", file=f)
或传统的字符串连接:
print(' '.join([str(s) for s in value]) + ' ', file=f)
我认为这会给你你想要的 output:
a = list(dictionary.values())
with open('test.txt', 'w') as f:
for item in a:
f.write(' '.join(item) + "\n")
更新:我最好用来自@deceze 的想法 go
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.