簡體   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