【发布时间】:2021-01-09 15:41:20
【问题描述】:
我有以下字典,其中包含每个值的列表
dictionary = {
0 : [2, 5]
1 : [1, 4]
2 : [3]
}
我需要在这样的文件中输出值
2 5
1 4
3
在每行的最后一位我需要有一个空格。
我已经尝试使用此代码
with open('test.txt', 'w') as f:
for value in dictionary.values():
f.write('{}\n'.format(value))
所以我想省略输出的 [] 和 ,。
我还尝试将字典的值保存到列表列表中,然后处理列表而不是字典。但这不是我想的最明智的事情。数字也以错误的顺序保存,括号和逗号也被保存。
a = list(dictionary.values())
for i in a:
with open('test.txt', 'w') as f:
for item in a:
f.write("%s\n" % item)
因为我得到了这个输出
[3, 2]
[5, 1]
[4]
【问题讨论】:
-
' '.join(value)…
标签: python file dictionary