第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問(wèn)題,去搜搜看,總會(huì)有你想問(wèn)的

使用 str.format() 和字典

使用 str.format() 和字典

為什么會(huì)這樣:data = {'first': 'Hodor', 'last': 'Hodor!'}print('{first} {last}'.format(**data))這有效:bdays = {    'Wesley Neill': 'January 6, 1985',    'Victoria Neill': 'August 25, 1992',    'Heather Neill': 'June 25, 1964'}print('\n {} \n {} \n {}'.format(*bdays))但這不起作用: print('\n {} \n {} \n {}'.format(**bdays))Traceback (most recent call last):  File "C:/Users/wesle/PycharmProjects/practicepython/birthdays.py", line 9, in <module>    print('We have the following names in our dictionary: \n {} \n {} \n {} \n'.format(**bdays))IndexError: tuple index out of range第一個(gè)示例在占位符大括號(hào)中包含字典鍵,并在參數(shù)中使用 **kwargs。第二個(gè)沒有鍵,在 .format() 參數(shù)中只有一個(gè)星號(hào)。第三個(gè)在占位符中沒有鍵,如示例 1 所示,但它確實(shí)在參數(shù)中使用了 **kwargs。我知道我需要做些什么才能使事情正常進(jìn)行,但我對(duì)這里的微妙之處感到好奇。
查看完整描述

2 回答

?
肥皂起泡泡

TA貢獻(xiàn)1829條經(jīng)驗(yàn) 獲得超6個(gè)贊

.format(**bdays)相當(dāng)于.format(key1=value, key2=value2,...)鍵是名稱,值是生日。


因此,要使其發(fā)揮作用,您的打印聲明需要成為 -


print('\n {Wesley Neill} \n {Victoria Neill} \n {Heather Neill}'.format(**bdays))

這將打印這 3 個(gè)人的生日。


在您的 python 控制臺(tái)中嘗試以下操作 -


>>> [*bdays]

['Wesley Neill', 'Victoria Neill', 'Heather Neill']


查看完整回答
反對(duì) 回復(fù) 2022-05-24
?
精慕HU

TA貢獻(xiàn)1845條經(jīng)驗(yàn) 獲得超8個(gè)贊

首先星號(hào)符號(hào)的作用:


**dict is equivalent to k1=v1, k2=v, ...

*dict is equivalent to [k1, k2, ...]

所以你在做:


# This print('{first} {last}'.format(**data)) is:

print('{first} {last}'.format(first='Hodor', last='Hodor!'))


# This print('\n {} \n {} \n {}'.format(*bdays)) is:

print('\n {} \n {} \n {}'.format(['Wesley Neill', 'Victoria Neill', 'Heather Neill']))


# This print('\n {} \n {} \n {}'.format(**bdays)) is:

print('\n {} \n {} \n {}'.format('Wesley Neill'='January 6, 1985', 'Victoria Neill'='August 25, 1992', 'Heather Neill'='June 25, 1964'))

最終格式字符串中沒有說(shuō)明任何鍵,因此您會(huì)收到錯(cuò)誤消息。


查看完整回答
反對(duì) 回復(fù) 2022-05-24
  • 2 回答
  • 0 關(guān)注
  • 145 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)