【问题标题】:Writing dictionary list values to a text file将字典列表值写入文本文件
【发布时间】: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


【解决方案1】:

您的第一个版本非常接近,所以让我们对其进行改进。

您可以做的是使用列表推导来遍历并将每个整数转换为字符串。然后在结果字符串列表上调用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)

【讨论】:

  • 只需用空格连接列表中的项目,不要尝试对其表示进行字符串操作。
  • @deceze 我的最新编辑是否解决了您的问题?
  • 非常感谢您的帮助。这不是 100% 必要的,但如果你可以让代码在每行的最后一个数字之后给我一个额外的空间,我会很高兴。 :)
  • @condoriano 似乎有点奇怪,你想要额外的尾随空格,但无论如何,我在答案中添加了一些方法
  • 有点奇怪是的。只是我不想弄乱读取 txt 文件的其余代码,默认情况下每行都有一个额外的尾随空格。
【解决方案2】:

我认为这会给你想要的输出:

a = list(dictionary.values())
with open('test.txt', 'w') as f:
    for item in a:
        f.write(' '.join(item) + "\n")

更新:我最好接受@deceze 的想法

【讨论】:

  • 根据您的建议,我收到此错误。 SyntaxError: can't use starred expression here
猜你喜欢
  • 1970-01-01
  • 2016-08-26
  • 1970-01-01
  • 2014-06-30
  • 1970-01-01
  • 2017-08-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多