Python中參數(shù)打包和解包的實(shí)現(xiàn)
我們使用兩個(gè)運(yùn)算符 *(用于元組)和 **(用于字典)。
考慮這樣一種情況:我們有一個(gè)函數(shù)接收四個(gè)參數(shù)。我們想調(diào)用這個(gè)函數(shù),我們有一個(gè)大小為4的列表,其中包含該函數(shù)的所有參數(shù)。如果我們簡(jiǎn)單地傳遞一個(gè)列表給函數(shù),調(diào)用就不起作用。
# A sample function that takes 4 arguments
# and prints them.
def fun(a, b, c, d):
print(a, b, c, d)
# Driver Code
my_list = [1, 2, 3, 4]
# This doesn't work
fun(my_list)輸出
TypeError: fun() takes exactly 4 arguments (1 given)
解包
我們可以使用 * 來解包列表,這樣它的所有元素都可以作為不同的參數(shù)傳遞。
# A sample function that takes 4 arguments
# and prints the,
def fun(a, b, c, d):
print(a, b, c, d)
# Driver Code
my_list = [1, 2, 3, 4]
# Unpacking list into four arguments
fun(*my_list)輸出
(1, 2, 3, 4)
需要記住參數(shù)的長(zhǎng)度必須與我們?yōu)閰?shù)解包的列表的長(zhǎng)度相同。
# Error when len(args) != no of actual arguments
# required by the function
args = [0, 1, 4, 9]
def func(a, b, c):
return a + b + c
# calling function with unpacking args
func(*args)輸出
Traceback (most recent call last):
File "/home/592a8d2a568a0c12061950aa99d6dec3.py", line 10, in <module>
func(*args)
TypeError: func() takes 3 positional arguments but 4 were given
再舉一個(gè)例子,考慮內(nèi)置的range()函數(shù),它需要單獨(dú)的開始和停止參數(shù)。如果它們不能單獨(dú)使用,請(qǐng)使用 *運(yùn)算符編寫函數(shù)調(diào)用,以將參數(shù)從列表或元組中解包:
>>> >>> range(3, 6) # normal call with separate arguments [3, 4, 5] >>> args = [3, 6] >>> range(*args) # call with arguments unpacked from a list [3, 4, 5]
打包
當(dāng)我們不知道有多少參數(shù)需要傳遞給Python函數(shù)時(shí),我們可以將所有參數(shù)打包到元組中。
# A Python program to demonstrate use
# of packing
# This function uses packing to sum
# unknown number of arguments
def mySum(*args):
return sum(args)
# Driver code
print(mySum(1, 2, 3, 4, 5))
print(mySum(10, 20))輸出
15
30
上面的函數(shù)mySum()進(jìn)行“打包”,將該方法調(diào)用接收到的所有參數(shù)打包到一個(gè)變量中。一旦我們有了這個(gè)’packed’變量,我們就可以用它來做我們用普通元組做的事情。args[0]和args[1]將分別給予第一個(gè)和第二個(gè)參數(shù)。由于我們的元組是不可變的,所以可以將args元組轉(zhuǎn)換為列表,這樣就可以修改、刪除和重新排列i中的項(xiàng)。
下面是一個(gè)展示打包和解包的示例。
# A Python program to demonstrate both packing and
# unpacking.
# A sample python function that takes three arguments
# and prints them
def fun1(a, b, c):
print(a, b, c)
# Another sample function.
# This is an example of PACKING. All arguments passed
# to fun2 are packed into tuple *args.
def fun2(*args):
# Convert args tuple to a list so we can modify it
args = list(args)
# Modifying args
args[0] = 'python'
args[1] = 'awesome'
# UNPACKING args and calling fun1()
fun1(*args)
# Driver code
fun2('Hello', 'beautiful', 'world!')輸出
(python, awesome, world!)
用于字典
# A sample program to demonstrate unpacking of
# dictionary items using **
def fun(a, b, c):
print(a, b, c)
# A call with unpacking of dictionary
d = {'a':2, 'b':4, 'c':10}
fun(**d)輸出
2 4 10
這里 ** 解包了與它一起使用的字典,并將字典中的項(xiàng)作為關(guān)鍵字參數(shù)傳遞給函數(shù)。所以寫“fun(1,**d)”相當(dāng)于寫“fun(1,b=4,c=10)”。
# A Python program to demonstrate packing of
# dictionary items using **
def fun(**kwargs):
# kwargs is a dict
print(type(kwargs))
# Printing dictionary items
for key in kwargs:
print("%s = %s" % (key, kwargs[key]))
# Driver code
fun(name="geeks", ID="101", language="Python")輸出
<class 'dict'>
name = geeks
ID = 101
language = Python
應(yīng)用和要點(diǎn)
- 在套接字編程中用于向服務(wù)器發(fā)送大量請(qǐng)求。
- 在Django框架中用于將變量參數(shù)發(fā)送到視圖函數(shù)。
- 有一些包裝函數(shù)要求我們傳入變量參數(shù)。
- 參數(shù)的修改變得很容易,所以必須小心使用它們。
到此這篇關(guān)于Python中參數(shù)打包和解包的實(shí)現(xiàn)的文章就介紹到這了,更多相關(guān)Python參數(shù)打包和解包內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Pytorch中accuracy和loss的計(jì)算知識(shí)點(diǎn)總結(jié)
在本片文章里小編給大家整理的是關(guān)于Pytorch中accuracy和loss的計(jì)算相關(guān)知識(shí)點(diǎn)內(nèi)容,有需要的朋友們可以學(xué)習(xí)下。2019-09-09
完美解決Python matplotlib繪圖時(shí)漢字顯示不正常的問題
今天小編就為大家分享一篇完美解決Python matplotlib繪圖時(shí)漢字顯示不正常的問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2019-01-01
pytorch?tensor內(nèi)所有元素相乘實(shí)例
這篇文章主要介紹了pytorch?tensor內(nèi)所有元素相乘實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-07-07
使用Python在Windows系統(tǒng)中創(chuàng)建多樣化彈窗的兩種方法
在 Windows 應(yīng)用開發(fā)中,彈窗(MessageBox)是與用戶交互的重要方式,Python 提供了多種方法來實(shí)現(xiàn)彈窗功能,本文將深入介紹使用Python在Windows系統(tǒng)中創(chuàng)建多樣化彈窗的兩種方法及其適用場(chǎng)景,需要的朋友可以參考下2025-12-12
django生產(chǎn)環(huán)境搭建(uWSGI+django+nginx+python+MySQL)
本文主要介紹了django生產(chǎn)環(huán)境搭建,主要包括uWSGI+django+nginx+python+MySQL,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-08-08
Python爬取智聯(lián)招聘數(shù)據(jù)分析師崗位相關(guān)信息的方法
這篇文章主要介紹了Python爬取智聯(lián)招聘數(shù)據(jù)分析師崗位相關(guān)信息的方法,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-08-08
python開發(fā)之字符串string操作方法實(shí)例詳解
這篇文章主要介紹了python開發(fā)之字符串string操作方法,以實(shí)例形式較為詳細(xì)的分析了Python針對(duì)字符串的轉(zhuǎn)義、連接、換行、輸出等操作技巧,需要的朋友可以參考下2015-11-11
pycharm 多行批量縮進(jìn)和反向縮進(jìn)快捷鍵介紹
這篇文章主要介紹了pycharm 多行批量縮進(jìn)和反向縮進(jìn)快捷鍵介紹,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2021-01-01
Python利用imshow制作自定義漸變填充柱狀圖(colorbar)
這篇文章主要介紹了Python利用imshow制作自定義漸變填充柱狀圖(colorbar),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-12-12

