簡體   English   中英

為什么輸出為11032? Python3.6

[英]Why will the output be 11032? Python3.6

d = {10:"x", 1:"wx", 2:"yz"}
a = d.setdefault(1)
b = d.setdefault(3)
s = "{}" * len(d)
print(s.format(*d))

為什么輸出為11032?

經過2次setdefault調用后,

d = {10: "x", 1: "wx", 2: "yz"}
d.setdefault(1)  # does not change the dictionary because there's already 1
d.setdefault(3)  # add 3 with value None (default if not speicfied)

d變為:

>>> d
{10: 'x', 1: 'wx', 2: 'yz', 3: None}

迭代字典收率字典鍵: 10, 1, 2, 3 (由*d執行的迭代將參數d解壓縮):

>>> for key in d:
...     print(key)
... 
10
1
2
3

因此, s.format(*d)等同於'{}{}{}{}'.format(10, 1, 2, 3) s.format(*d) '{}{}{}{}'.format(10, 1, 2, 3)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM