繁体   English   中英

使用格式方法打印字典内容

[英]Printing dictionary contents using format method

我刚开始学习python,并尝试使用format函数打印字典内容。 我在阅读https://www.python-course.eu/python3_formatted_output.php时获得了一些见识

问题1:double *运算符用于执行指数计算,它与字典的行为如何?

问题2:对于此代码块,我得到IndexError: tuple index out of range 我一定误解了一些东西。

students = {100 : "Udit", 101 : "Rohan", 102 : "Akash", 103 : "Rajul"}
for student in students :
    format_string = str(student) + ": {" + str(student) + "}"
    print(format_string)
    print(format_string.format(**students))

您这样迭代:

for student in students :

由于students是字典,因此会遍历数字之类的键,例如100 ,这意味着最终要构建如下格式的字符串:

'100: {100}'

然后,当您调用format时, 100要求输入位置参数#100。 但是您只传递了0。因此,您得到了IndexError

当dict键是有效的字符串格式键时,您只能有用地使用format(**students)语法。


同时,我不知道谁一直在传播format(**d)是个好主意。 如果您只想使用字典或其他映射进行格式化,那就是在3.2中添加了format_map目的:

print(format_string.format_map(students))

一个优点是,当您做错了什么时,您会收到一条更有用的错误消息:

ValueError: Format string contains positional fields

看到它时,您可以打印出格式字符串本身,并看到{100} ,是的,这是一个位置字段。 所需的调试少得多。

更重要的是,它无需关键字喷溅即可轻松阅读和理解。 而且它甚至更有效(在3.6中不如在3.2中那么高,但是format仍然必须建立一个新的dict副本,而format_map可以使用您format_map原样使用的任何映射)。


最后,像这样动态地构建格式字符串很少是一个好主意。 打印您要打印的内容的一种简单得多的方法是:

for num, student in students.items():
    print(f'{num}: {student}')

或者,如果您不使用3.6,或者只是想显式地使用formatformat_map而不是f字符串,则具有相同的想法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM