Python以句法簡(jiǎn)單、簡(jiǎn)潔而聞名,只需掌握簡(jiǎn)單的英語(yǔ)就能理解其代碼。對(duì)初學(xué)者來(lái)說(shuō)極具吸引力,它沒(méi)有聲明,沒(méi)有花哨的字符或者奇怪的句法。正因如此,Python才得以風(fēng)靡全球。
除此之外,Python還具備一些很酷的特點(diǎn),比如裝飾器和列表解析。這些特點(diǎn)確實(shí)能創(chuàng)造奇跡,但*也值得這一美名,小小字符能帶來(lái)翻天覆地的變化。
先從一個(gè)小技巧開(kāi)始:
In [1]:
first_dict= {‘key1’: ‘hello’, ‘key2’: ‘world’}
second_dict= {‘key3’: ‘whats’, ‘key4’: ‘up’}
In [2]:
#joins the dicts
combined_dict= {**first_dict, **second_dict}
combined_dict
Out[2]:
{‘key1’: ‘hello’, ‘key2’: ‘world’, ‘key3’:‘whats’, ‘key4’: ‘up’}
In [ ]:
這是合并字典的超簡(jiǎn)單方法!你能明顯看出,我僅用了幾個(gè)星號(hào)就將字典結(jié)合了起來(lái),我接下來(lái)會(huì)一一解釋。
星號(hào)在哪些地方發(fā)揮作用?
除了眾所周知的乘法作用,星號(hào)還能讓你輕松完成一些重要任務(wù),例如解包。一般來(lái)說(shuō),你可以使用星號(hào)來(lái)解包可迭代對(duì)象,也能對(duì)雙向可迭代對(duì)象(就像字典一樣)進(jìn)行雙重解包。
In [7]:
# unpackingan iterable
[xfor x inrange(100)] == [*range(100)]
Out[7]:
True
In [8]:
#unpkacing dict keys
d = {‘key1’: ‘A’}
list(d.keys()) == [*d]
Out[8]:
True
In [9]:
#unpacking whole dict
d == {**d}
Out[9]:
True
解包的力量
不要破壞別人的代碼
大家也越來(lái)越理解這一點(diǎn),但仍然有人沒(méi)有遵守。開(kāi)發(fā)者寫(xiě)出的每一個(gè)函數(shù)都有其特征。如果函數(shù)被改變,那么所有基于你的代碼而撰寫(xiě)的代碼都會(huì)被破壞。
我將介紹一種簡(jiǎn)單的方法,你可以為自己的函數(shù)增添更多功能性,同時(shí)也不會(huì)破壞其向后兼容性,最后你會(huì)得到更多的模塊化代碼。
在你的代碼中輸入*args和**kwrags,它們會(huì)將所有輸入都解包進(jìn)函數(shù)。單星號(hào)針對(duì)標(biāo)準(zhǔn)的可迭代對(duì)象,雙星號(hào)針對(duì)字典類的雙向可迭代對(duì)象,舉例說(shuō)明:
In [1]:
defversion1(a, b):
print(a)
print(b)
In [2]:
version1(4,5)
4
5
In [3]:
#code breaks
version1(4,5,6)
---------------------------------------------------------------------------
TypeError Traceback(most recent call last)
《ipython-input-3-b632c039a799》 in《module》
1# code breaks
----》 2 version1(4,5,6)
TypeError: version1() takes 2 positionalarguments but 3 were given
In [4]:
defversion2(a, b, *args):
print(a)
print(b)
# new function.
if args:
for c in args:
print(c)
In [5]:
version2(1,2,3,4,5)
1
2
3
4
5
In [6]:
#code breaks
version2(1,2,3,4,5, Extra=10)
---------------------------------------------------------------------------
TypeError Traceback(most recent call last)
《ipython-input-6-748b0aef9e5d》in 《module》
1 # code breaks
----》 2 version2(1,2,3,4,5, Extra=10)
TypeError: version2() got an unexpectedkeyword argument ‘Extra’
In [7]:
defversion3(a, b , *args, **kwrags):
print(a)
print(b)
# new function.
if args:
for c in args:
print(c)
if kwrags:
for key, value inzip(kwrags.keys(), kwrags.values()):
print(key,‘:’, value)
In [8]:
version3(1,2,3,4,5, Extra=10)
1
2
3
4
5
Extra : 10
In [ ]:
工作代碼和破解代碼
這個(gè)例子展示了如何使用args和kwargs來(lái)接收之后的參數(shù),并留到將來(lái)使用,同時(shí)也不會(huì)破壞你函數(shù)中原有的call函數(shù)。
星號(hào)是Python中很重要的一部分,但卻常常被我們忽略。事實(shí)上,我們平常沒(méi)有注意到的關(guān)鍵點(diǎn)還有很多,值得我們?nèi)ヒ稽c(diǎn)點(diǎn)探索。
-
代碼
+關(guān)注
關(guān)注
30文章
4834瀏覽量
69115 -
python
+關(guān)注
關(guān)注
56文章
4809瀏覽量
85070 -
語(yǔ)法
+關(guān)注
關(guān)注
0文章
44瀏覽量
9869
發(fā)布評(píng)論請(qǐng)先 登錄
相關(guān)推薦
5種Python實(shí)現(xiàn)方式詳解
python編寫(xiě)條件分支的最佳實(shí)踐
python代碼示例之基于Python的日歷api調(diào)用代碼實(shí)例
![<b class='flag-5'>python</b><b class='flag-5'>代碼</b>示例之基于<b class='flag-5'>Python</b>的日歷api調(diào)用<b class='flag-5'>代碼</b>實(shí)例](https://file.elecfans.com/web1/M00/63/17/o4YBAFuQy8-AO90pAAAei-DUxgU163.png)
評(píng)論