我试图在字典上使用Python的pprint,但由于某种原因,它不起作用。下面是我的代码(我使用PyCharm Pro作为我的IDE):
from pprint import pprint
message = "Come on Eileen!"
count = {}
for character in message:
count.setdefault(character, 0)
count[character] += 1
pprint(count)这是我的输出:
{' ': 2, '!': 1, 'C': 1, 'E': 1, 'e': 3, 'i': 1, 'l': 1, 'm': 1, 'n': 2, 'o': 2}如果能提供任何帮助,我们将不胜感激。
发布于 2016-08-20 22:24:20
输出是完全正确和预期的。来自 module documentation
如果可以的话,格式化的表示将对象保持在一行上,如果对象不适合于允许的宽度,则将它们拆分为多行。
大胆强调我的。
您可以将width关键字参数设置为1,以强制将每个键值对打印在单独的行上:
>>> pprint(count, width=1)
{' ': 2,
'!': 1,
'C': 1,
'E': 1,
'e': 3,
'i': 1,
'l': 1,
'm': 1,
'n': 2,
'o': 2}发布于 2020-06-09 13:57:47
您必须指定第二个参数,即
pprint.pprint(count, width=1)或者在你的情况下
pprint(count, width=1)输出:
{' ': 2,
'!': 1,
'C': 1,
'E': 1,
'e': 3,
'i': 1,
'l': 1,
'm': 1,
'n': 2,
'o': 2}发布于 2019-10-16 19:41:37
我在练习时遇到了同样的问题,然后我意识到我正在一次又一次地运行旧的characterCount.py,而不是运行新的漂亮字符Count.py文件。尝试单击顶部的“运行”按钮,然后选择正确的文件并再次运行。
https://stackoverflow.com/questions/39059195
复制相似问题