創(chuàng)新互聯(lián)www.cdcxhl.cn八線(xiàn)動(dòng)態(tài)BGP香港云服務(wù)器提供商,新人活動(dòng)買(mǎi)多久送多久,劃算不套路!
Python傳遞任意數(shù)量實(shí)參的方法?這個(gè)問(wèn)題可能是我們?nèi)粘W(xué)習(xí)或工作經(jīng)常見(jiàn)到的。希望通過(guò)這個(gè)問(wèn)題能讓你收獲頗深。下面是小編給大家?guī)?lái)的參考內(nèi)容,讓我們一起來(lái)看看吧!
傳遞任意數(shù)量的實(shí)參
形參前加一個(gè) * ,Python會(huì)創(chuàng)建一個(gè)已形參為名的空元組,將所有收到的值都放到這個(gè)元組中:
def make_pizza(*toppings): print("\nMaking a pizza with the following toppings: ") for topping in toppings: print("- " + topping) make_pizza('pepperoni') make_pizza('mushroom', 'green peppers', 'extra cheese')
不管函數(shù)收到多少實(shí)參,這種語(yǔ)法都管用。
1. 結(jié)合使用位置實(shí)參和任意數(shù)量實(shí)參
def make_pizza(size, *toppings): print("\nMaking a " + str(size) + "-inch pizza with the following toppings: ") for topping in toppings: print("- " + topping) make_pizza(16, 'pepperoni') make_pizza(12, 'mushroom', 'green peppers', 'extra cheese')
運(yùn)行結(jié)果:
Making a 16-inch pizza with the following toppings: - pepperoni Making a 12-inch pizza with the following toppings: - mushroom - green peppers - extra cheese
2. 使用任意數(shù)量的關(guān)鍵字實(shí)參
def build_profile(first, last, **user_info): profile = dict() profile['first_name'] = first profile['last_name'] = last for key, value in user_info.items(): profile[key] = value return profile user_profile = build_profile('albert', 'einstein', location='princeton', field='physic') print(user_profile)
形參**user_info中的兩個(gè)星號(hào)讓python創(chuàng)建了一個(gè)名為user_info的空字典。
感謝各位的閱讀!看完上述內(nèi)容,你們對(duì)Python傳遞任意數(shù)量實(shí)參的方法大概了解了嗎?希望文章內(nèi)容對(duì)大家有所幫助。如果想了解更多相關(guān)文章內(nèi)容,歡迎關(guān)注創(chuàng)新互聯(lián)-成都網(wǎng)站建設(shè)公司行業(yè)資訊頻道。
文章題目:Python傳遞任意數(shù)量實(shí)參的方法-創(chuàng)新互聯(lián)
標(biāo)題URL:http://chinadenli.net/article30/deeepo.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供云服務(wù)器、營(yíng)銷(xiāo)型網(wǎng)站建設(shè)、網(wǎng)站改版、移動(dòng)網(wǎng)站建設(shè)、手機(jī)網(wǎng)站建設(shè)、動(dòng)態(tài)網(wǎng)站
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶(hù)投稿、用戶(hù)轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話(huà):028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容