python中前綴運(yùn)算符 *和 **的用法示例詳解
這篇主要探討 ** 和 * 前綴運(yùn)算符,**在變量之前使用的*and **運(yùn)算符.
一個(gè)星(*):表示接收的參數(shù)作為元組來(lái)處理
兩個(gè)星(**):表示接收的參數(shù)作為字典來(lái)處理
簡(jiǎn)單示例:
>>> numbers = [2, 1, 3, 4, 7] >>> more_numbers = [*numbers, 11, 18] >>> print(*more_numbers, sep=', ') 2, 1, 3, 4, 7, 11, 18
用途:
- 使用 * 和 ** 將參數(shù)傳遞給函數(shù)
- 使用**和**捕獲傳遞給函數(shù)的參數(shù)
- 使用*只接受關(guān)鍵字參數(shù)
- 使用*元組拆包過(guò)程中捕獲項(xiàng)目
- 使用*解包iterables到一個(gè)列表/元組
- 使用**要解壓縮詞典到其他字典
例子解釋:
1.調(diào)用函數(shù)時(shí),*可以使用運(yùn)算符將可迭代對(duì)象解壓縮為函數(shù)調(diào)用中的參數(shù):
>>> fruits = ['lemon', 'pear', 'watermelon', 'tomato'] >>> print(fruits[0], fruits[1], fruits[2], fruits[3]) lemon pear watermelon tomato >>> print(*fruits) lemon pear watermelon tomato
該print(*fruits)行將fruits列表中的所有項(xiàng)目print作為單獨(dú)的參數(shù)傳遞到函數(shù)調(diào)用中,而我們甚至不需要知道列表中有多少個(gè)參數(shù)。
2.** 運(yùn)算符允許我們采取鍵值對(duì)的字典,并把它解壓到函數(shù)調(diào)用中的關(guān)鍵字參數(shù)。
>>> date_info = {'year': "2020", 'month': "01", 'day': "01"} >>> filename = "{year}-{month}-{day}.txt".format(**date_info) >>> filename '2020-01-01.txt'
** 將關(guān)鍵字參數(shù)解包到函數(shù)調(diào)用中并不是很常見(jiàn)。我最常看到的地方是練習(xí)繼承時(shí):super()通常要同時(shí)包含*和**。
雙方*并 **可以在函數(shù)調(diào)用中多次使用,像Python 3.5的。
>> fruits = ['lemon', 'pear', 'watermelon', 'tomato'] >>> numbers = [2, 1, 3, 4, 7] >>> print(*numbers, *fruits) 2 1 3 4 7 lemon pear watermelon tomato **多次使用類似: >>> date_info = {'year': "2020", 'month': "01", 'day': "01"} >>> track_info = {'artist': "Beethoven", 'title': 'Symphony No 5'} >>> filename = "{year}-{month}-{day}-{artist}-{title}.txt".format( ... **date_info, ... **track_info, ... ) >>> filename '2020-01-01-Beethoven-Symphony No 5.txt'
3.定義函數(shù)時(shí),*可以使用運(yùn)算符捕獲為函數(shù)提供的無(wú)限數(shù)量的位置參數(shù)。這些參數(shù)被捕獲到一個(gè)元組中。
from random import randint def roll(*dice): return sum(randint(1, die) for die in dice
4.我們可以用**定義一個(gè)函數(shù)時(shí),捕捉給予功能到字典中的任何關(guān)鍵字參數(shù):
def tag(tag_name, **attributes): attribute_list = [ f'{name}="{value}"' for name, value in attributes.items() ] return f"<{tag_name} {' '.join(attribute_list)}>"
5.帶有僅關(guān)鍵字參數(shù)的位置參數(shù),要接受僅關(guān)鍵字的參數(shù),可以*在定義函數(shù)時(shí)在使用后放置命名參數(shù)
def get_multiple(*keys, dictionary, default=None): return [ dictionary.get(key, default) for key in keys ] 上面的函數(shù)可以這樣使用: >>> fruits = {'lemon': 'yellow', 'orange': 'orange', 'tomato': 'red'} >>> get_multiple('lemon', 'tomato', 'squash', dictionary=fruits, default='unknown') ['yellow', 'red', 'unknown']
參數(shù)dictionaryand default在其后*keys,這意味著只能將它們指定為關(guān)鍵字參數(shù)。如果我們嘗試在位置上指定它們,則會(huì)收到錯(cuò)誤消息:
>>> fruits = {'lemon': 'yellow', 'orange': 'orange', 'tomato': 'red'} >>> get_multiple('lemon', 'tomato', 'squash', fruits, 'unknown') Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: get_multiple() missing 1 required keyword-only argument: 'dictionary'
6.不帶位置參數(shù)的僅關(guān)鍵字參數(shù)
僅關(guān)鍵字參數(shù)的功能很酷,但是如果您需要僅關(guān)鍵字參數(shù)而不捕獲無(wú)限的位置參數(shù)怎么辦?
def with_previous(iterable, *, fillvalue=None): """Yield each iterable item along with the item before it.""" previous = fillvalue for item in iterable: yield previous, item previous = item ```
該函數(shù)接受一個(gè)iterable參數(shù),該參數(shù)可以在位置上指定(作為第一個(gè)參數(shù)),也可以通過(guò)其名稱和作為fillvalue僅關(guān)鍵字參數(shù)的參數(shù)來(lái)指定。這意味著我們可以這樣調(diào)用with_previous:
>>> list(with_previous([2, 1, 3], fillvalue=0)) [(0, 2), (2, 1), (1, 3)] 但不是這樣的: >>> list(with_previous([2, 1, 3], 0)) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: with_previous() takes 1 positional argument but 2 were given 此函數(shù)接受兩個(gè)參數(shù),并且其中一個(gè)fillvalue 必須指定為關(guān)鍵字arguments。
7.元組拆包中的星號(hào)
Python 3還添加了一種新的使用運(yùn)算符的方式,該方式僅與上面的-when-defining-a-function和*-when-when-calling-afunction功能有關(guān)。
>>> fruits = ['lemon', 'pear', 'watermelon', 'tomato'] >>> first, second, *remaining = fruits >>> remaining ['watermelon', 'tomato'] >>> first, *remaining = fruits >>> remaining ['pear', 'watermelon', 'tomato'] >>> first, *middle, last = fruits >>> middle ['pear', 'watermelon']
8.列表文字中的星號(hào)
Python 3.5 通過(guò)PEP 448引入了大量的新功能。最大的新功能之一是能夠?qū)⒖傻鷮?duì)象轉(zhuǎn)儲(chǔ)到新列表中。
假設(shè)您有一個(gè)函數(shù),該函數(shù)可以接收任何序列,并返回一個(gè)列表,其中該序列與該序列的反序連接在一起:
def palindromify(sequence): return list(sequence) + list(reversed(sequence))
該函數(shù)需要將事物轉(zhuǎn)換為列表幾次,以連接列表并返回結(jié)果。在Python 3.5中,我們可以改為輸入:
def palindromify(sequence): return [*sequence, *reversed(sequence)]
此代碼刪除了一些不必要的列表調(diào)用,因此我們的代碼更加高效和可讀。
這是另一個(gè)例子:
def rotate_first_item(sequence): return [*sequence[1:], sequence[0]]
該函數(shù)返回一個(gè)新列表,其中給定列表(或其他序列)中的第一項(xiàng)移動(dòng)到新列表的末尾。
* 運(yùn)算符的這種使用是將不同類型的可迭代對(duì)象連接在一起的好方法。的*操作者適用于任何可迭代,而使用+操作者僅適用于具有所有相同類型的特定序列。
這不僅限于創(chuàng)建列表。我們還可以將可迭代項(xiàng)轉(zhuǎn)儲(chǔ)到新的元組或集合中:
>>> fruits = ['lemon', 'pear', 'watermelon', 'tomato'] >>> (*fruits[1:], fruits[0]) ('pear', 'watermelon', 'tomato', 'lemon') >>> uppercase_fruits = (f.upper() for f in fruits) >>> {*fruits, *uppercase_fruits} {'lemon', 'watermelon', 'TOMATO', 'LEMON', 'PEAR', 'WATERMELON', 'tomato', 'pear'}
請(qǐng)注意,上面的最后一行獲取一個(gè)列表和一個(gè)生成器,并將它們轉(zhuǎn)儲(chǔ)到新集中。在使用之前*,以前沒(méi)有一種簡(jiǎn)單的方法可以在一行代碼中做到這一點(diǎn)。以前有一種方法可以做到,但要記住或發(fā)現(xiàn)它并不容易:
>>> set().union(fruits, uppercase_fruits) {'lemon', 'watermelon', 'TOMATO', 'LEMON', 'PEAR', 'WATERMELON', 'tomato', 'pear'}
9.字典文字中的雙星號(hào)
PEP 448還**允許該運(yùn)算符用于將鍵/值對(duì)從一個(gè)字典轉(zhuǎn)儲(chǔ)到新字典中,從而擴(kuò)展了功能:
>>> date_info = {'year': "2020", 'month': "01", 'day': "01"} >>> track_info = {'artist': "Beethoven", 'title': 'Symphony No 5'} >>> all_info = {**date_info, **track_info} >>> all_info {'year': '2020', 'month': '01', 'day': '01', 'artist': 'Beethoven', 'title': 'Symphony No 5'}
例如,我們可以在添加新值的同時(shí)復(fù)制字典:
>>> date_info = {'year': '2020', 'month': '01', 'day': '7'} >>> event_info = {**date_info, 'group': "Python Meetup"} >>> event_info {'year': '2020', 'month': '01', 'day': '7', 'group': 'Python Meetup'}
或在覆蓋特定值的同時(shí)復(fù)制/合并字典:
>>> event_info = {'year': '2020', 'month': '01', 'day': '7', 'group': 'Python Meetup'} >>> new_info = {**event_info, 'day': "14"} >>> new_info {'year': '2020', 'month': '01', 'day': '14', 'group': 'Python Meetup'}
ref: https://treyhunner.com/2018/10/asterisks-in-python-what-they-are-and-how-to-use-them/
總結(jié)
到此這篇關(guān)于python中前綴運(yùn)算符 *和 **的用法示例詳解的文章就介紹到這了,更多相關(guān)python中 *和 **的用法內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python中實(shí)現(xiàn)兩個(gè)字典(dict)合并的方法
這篇文章主要介紹了Python中實(shí)現(xiàn)兩個(gè)字典(dict)合并的方法,是Python程序設(shè)計(jì)中非常實(shí)用的技巧,需要的朋友可以參考下2014-09-09Python OpenCV處理圖像之圖像像素點(diǎn)操作
這篇文章主要為大家詳細(xì)介紹了Python OpenCV處理圖像之圖像像素點(diǎn)操作,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-07-07python使用Tesseract庫(kù)識(shí)別驗(yàn)證
這篇文章主要為大家詳細(xì)介紹了python使用Tesseract庫(kù)識(shí)別驗(yàn)證,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-03-03python suds訪問(wèn)webservice服務(wù)實(shí)現(xiàn)
這篇文章主要介紹了python suds訪問(wèn)webservice服務(wù)實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-06-06基于pytorch實(shí)現(xiàn)運(yùn)動(dòng)鞋品牌識(shí)別功能
這篇文章主要給大家介紹了關(guān)于如何基于pytorch實(shí)現(xiàn)運(yùn)動(dòng)鞋品牌識(shí)別功能,文中通過(guò)圖文以及實(shí)例代碼介紹的非常詳細(xì),對(duì)大家學(xué)習(xí)或者使用PyTorch具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2024-02-02python冒泡排序簡(jiǎn)單實(shí)現(xiàn)方法
這篇文章主要介紹了python冒泡排序簡(jiǎn)單實(shí)現(xiàn)方法,實(shí)例分析了Python冒泡排序的簡(jiǎn)單實(shí)現(xiàn)技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-07-07