如何使用Python中的*args和kwargs
在Python編程中,*args和kwargs是非常有用的工具,特別是當(dāng)需要處理未知數(shù)量的參數(shù)時(shí)。本文將介紹如何使用*args和kwargs。打開Python,新建一個(gè)空白的PY文檔。 *args首先
在Python編程中,*args和kwargs是非常有用的工具,特別是當(dāng)需要處理未知數(shù)量的參數(shù)時(shí)。本文將介紹如何使用*args和kwargs。
打開Python,新建一個(gè)空白的PY文檔。
*args
首先,我們用for循環(huán)來打印list中的所有值。
```python
def new_students(*args):
for all_students in args:
print(all_students)
the_list ["Peter", "Cherry", "Ben", "Ken", "Lee"]
new_students(*the_list)
```
如果不加*,則只會(huì)整個(gè)列表呈現(xiàn)出來,而不是只返回其中的值。
雖然可以使用普通方法打印列表中的值,但如果列表很長,則會(huì)造成很大的工作量,并且容易出錯(cuò)。因此,*args可以很好地解決這個(gè)問題。
另外,增加兩個(gè)變量在列表前面也不影響使用。
```python
def new_students(*args):
for all_students in args:
print(all_students)
the_list ("Peter", "Cherry", "Ben", "Ken", "Lee")
new_students(*the_list)
```
除了list,tuples也是可以運(yùn)用得上。
kwargs
kwargs對(duì)應(yīng)的要用字典(dictionary)。下面是一個(gè)例子:
```python
def details(kwargs):
for key, value in ():
print(key)
print(value)
contact {"Peter":"18", "Alice":"16", "Ben":"17"}
details(contact)
```
這將打印出字典中的鍵和值。
總之,*args和kwargs是在Python編程中非常有用的工具。使用它們可以更有效地處理函數(shù)的輸入?yún)?shù),并且能夠更輕松地處理不確定數(shù)量的參數(shù)。