【问题标题】:How do I get my dictionary values to print on the same line as the keys? [duplicate]如何让我的字典值与键打印在同一行? [复制]
【发布时间】:2019-05-02 17:11:15
【问题描述】:

我尝试在我的打印语句末尾添加 (end = ""),但值继续打印在新行上

for line in file:
    errorDict[line] = errorDict.get(line, 0) + 1

for i, n in errorDict.items():
    print (str(i) + str(":") + str(n))

目前看起来是这样的

5262200
:2
5DAA200
:1
531G200
:3
5700H3H
:1
5300A52
:2

我希望它看起来像

5262200 : 2
5DAA200 : 1
531G200 : 3
5700H3H : 1
5300A52 : 2

【问题讨论】:

  • str(i).rstrip()
  • errorDict = collections.Counter(line.rstrip("\n") for line in file).

标签: python dictionary printing


【解决方案1】:

您的 dict 中的键似乎在末尾有一个换行符。你可以在打印前strip()他们。

print (str(i).rstrip() + str(":") + str(n))

或在添加到字典之前:

errorDict[line.strip()] = errorDict.get(line, 0) + 1

【讨论】:

  • 后者可能是更好的主意。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-06-29
  • 1970-01-01
  • 2018-08-06
  • 1970-01-01
  • 2019-05-13
  • 2021-08-17
  • 1970-01-01
相关资源
最近更新 更多