python中前綴運算符 *和 **的用法示例詳解
這篇主要探討 ** 和 * 前綴運算符,**在變量之前使用的*and **運算符.
一個星(*):表示接收的參數(shù)作為元組來處理
兩個星(**):表示接收的參數(shù)作為字典來處理
簡單示例:
>>> 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ù)
- 使用*元組拆包過程中捕獲項目
- 使用*解包iterables到一個列表/元組
- 使用**要解壓縮詞典到其他字典
例子解釋:
1.調(diào)用函數(shù)時,*可以使用運算符將可迭代對象解壓縮為函數(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列表中的所有項目print作為單獨的參數(shù)傳遞到函數(shù)調(diào)用中,而我們甚至不需要知道列表中有多少個參數(shù)。
2.** 運算符允許我們采取鍵值對的字典,并把它解壓到函數(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)用中并不是很常見。我最常看到的地方是練習(xí)繼承時:super()通常要同時包含*和**。
雙方*并 **可以在函數(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ù)提供的無限數(shù)量的位置參數(shù)。這些參數(shù)被捕獲到一個元組中。
from random import randint def roll(*dice): return sum(randint(1, die) for die in dice
4.我們可以用**定義一個函數(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ù)
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ù)。如果我們嘗試在位置上指定它們,則會收到錯誤消息:
>>> 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ù)而不捕獲無限的位置參數(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ù)接受一個iterable參數(shù),該參數(shù)可以在位置上指定(作為第一個參數(shù)),也可以通過其名稱和作為fillvalue僅關(guān)鍵字參數(shù)的參數(shù)來指定。這意味著我們可以這樣調(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ù)接受兩個參數(shù),并且其中一個fillvalue 必須指定為關(guān)鍵字arguments。
7.元組拆包中的星號
Python 3還添加了一種新的使用運算符的方式,該方式僅與上面的-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.列表文字中的星號
Python 3.5 通過PEP 448引入了大量的新功能。最大的新功能之一是能夠?qū)⒖傻鷮ο筠D(zhuǎn)儲到新列表中。
假設(shè)您有一個函數(shù),該函數(shù)可以接收任何序列,并返回一個列表,其中該序列與該序列的反序連接在一起:
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)用,因此我們的代碼更加高效和可讀。
這是另一個例子:
def rotate_first_item(sequence): return [*sequence[1:], sequence[0]]
該函數(shù)返回一個新列表,其中給定列表(或其他序列)中的第一項移動到新列表的末尾。
* 運算符的這種使用是將不同類型的可迭代對象連接在一起的好方法。的*操作者適用于任何可迭代,而使用+操作者僅適用于具有所有相同類型的特定序列。
這不僅限于創(chuàng)建列表。我們還可以將可迭代項轉(zhuǎn)儲到新的元組或集合中:
>>> 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'}
請注意,上面的最后一行獲取一個列表和一個生成器,并將它們轉(zhuǎn)儲到新集中。在使用之前*,以前沒有一種簡單的方法可以在一行代碼中做到這一點。以前有一種方法可以做到,但要記住或發(fā)現(xiàn)它并不容易:
>>> set().union(fruits, uppercase_fruits) {'lemon', 'watermelon', 'TOMATO', 'LEMON', 'PEAR', 'WATERMELON', 'tomato', 'pear'}
9.字典文字中的雙星號
PEP 448還**允許該運算符用于將鍵/值對從一個字典轉(zhuǎn)儲到新字典中,從而擴展了功能:
>>> 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'}
例如,我們可以在添加新值的同時復(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'}
或在覆蓋特定值的同時復(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中前綴運算符 *和 **的用法示例詳解的文章就介紹到這了,更多相關(guān)python中 *和 **的用法內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python中實現(xiàn)兩個字典(dict)合并的方法
這篇文章主要介紹了Python中實現(xiàn)兩個字典(dict)合并的方法,是Python程序設(shè)計中非常實用的技巧,需要的朋友可以參考下2014-09-09python suds訪問webservice服務(wù)實現(xiàn)
這篇文章主要介紹了python suds訪問webservice服務(wù)實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧2020-06-06