【问题标题】:How do i insert a new line after every dictionary key pair print using dictionary comprehension as done by the pprint function in Python?如何使用 Python 中的 pprint 函数完成的字典理解在每个字典键对打印后插入新行?
【发布时间】:2019-12-16 13:30:28
【问题描述】:

从 pprint 导入 pprint MyDict={"a":list(range(1,10)),"b":list(range(11,20)),"c":list(range(21,30))} pprint((MyDict))

【问题讨论】:

  • 拜托,我不想使用漂亮打印功能“pprint”
  • 请发布预期的输出。
  • #thanks,这是一个带有 pprint {'a': [1, 2, 3, 4, 5, 6, 7, 8, 9], 'b': [11, 12, 13, 14, 15, 16, 17, 18, 19], 'c': [21, 22, 23, 24, 25, 26, 27, 28, 29]}
  • 这是我运行您的代码时得到的。使用您要查找的格式将此添加到问题中。

标签: python printing line new-operator


【解决方案1】:

这就是你要找的吗?

MyDict={"a":list(range(1,10)),"b":list(range(11,20)), "c":list(range(21,30))}

for key in MyDict:
    print(key, MyDict[key])

【讨论】:

  • 感谢 Nuno,这正是我想要的输出。但是我想知道如何在打印语句中使用 '\n' 来实现相同的效果。特别是如果我使用字典理解。
【解决方案2】:
for k,v in MyDict.items():
   print(k + ':' +' '+ v.__str__() +',')

【讨论】:

  • 谢谢一百万,这正是我要找的。虽然我想在字典理解中使用这样的代码 print({k + ':' +' '+ v.__str__() +',' for k,v in MyDict.items() })
【解决方案3】:
print(*(' '.join(map(str, x)) for x in MyDict.items()), sep='\n')

【讨论】:

  • 感谢 Jordan,这会产生所需的输出。我仍在试图弄清楚通配符(*)的作用。您能否指导我访问一些在线资源,我可以在其中阅读更多信息?谢谢
  • 星号告诉 Python 将所有值作为参数传递,而不是将容器作为单个参数传递。例如。 print(*(1, 2, 3))print(1, 2, 3) 相同。您可以在 Python 文档中找到更多详细信息:docs.python.org/2.7/reference/expressions.html#calls
猜你喜欢
  • 2013-12-09
  • 2021-04-12
  • 1970-01-01
  • 2014-12-26
  • 1970-01-01
  • 2011-11-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多