2021-01-18 python 中的內(nèi)置高級(jí)函數(shù)

[python 中的內(nèi)置高級(jí)函數(shù)]

1.map(function,iterable)

map是把迭代對(duì)象依次進(jìn)行函數(shù)運(yùn)算,并返回。

例子:

image

map返回的十分map對(duì)象,需要list()函數(shù)轉(zhuǎn)化。

2.exec()函數(shù)

執(zhí)行儲(chǔ)存在字符串或文件中的 Python 語(yǔ)句,相比于 eval,exec可以執(zhí)行更復(fù)雜的 Python 代碼。

Execute the given source in the context of globals and locals. 在全局變量和局部變量上下文中執(zhí)行給定的源。

The source may be a string representing one or more Python statements or a code object as returned by compile().
The globals must be a dictionary and locals can be any mapping, defaulting to the current globals and locals.
全局變量必須是一個(gè)字典類型,局部變量可以是任何映射
If only globals is given, locals defaults to it.
如果僅僅給訂全局變量,局部變量也默認(rèn)是它。

執(zhí)行單行語(yǔ)句

exec('print("Hello World")')

執(zhí)行多行語(yǔ)句

exec("""
for i in range(10):
print(i,end=",")
""")

運(yùn)行結(jié)果
Hello World
0,1,2,3,4,5,6,7,8,9,

x = 10  # global
expr = """
z = 30
sum = x + y + z
print(sum)
print("x= ",x)
print("y= ",y)
print("z= ",z)
"""

def func():
y = 20 #局部變量
exec(expr)
exec(expr, {'x': 1, 'y': 2})
exec(expr, {'x': 1, 'y': 2}, {'y': 3, 'z': 4})

# python尋找變量值的順尋,LEGB
# L->Local 局部變量
# E->Enclosing function locals 函數(shù)內(nèi)空間變量
# G->global 全局變量
# B-> bulltlins
# 局部變量———閉包空間———全局變量———內(nèi)建模塊
func()

結(jié)果是:

60
x= 10 ,y= 20,z= 30
33
x= 1 ,y= 2, z= 30
34
x= 1 ,y= 3 ,z= 30</pre>

python 中尋找變量順序:
LEGB
L-Local
E->enclose function local
G->global
B->bultins
局部變量->函數(shù)體內(nèi)變量-》全局變量-》內(nèi)置函數(shù)

3.zip()函數(shù)

zip() is a built-in Python function that gives us an iterator of tuples.

for i in zip([1,2,3],['a','b','c']):

print(i)
結(jié)果:
(1,'a')
(2, 'b')
(3, 'c')

image
image

zip將可迭代對(duì)象作為參數(shù),將對(duì)象中對(duì)應(yīng)的元素打包組成一個(gè)個(gè)元組,然后返回這些元組組成的列表。

而zip(*c)則是將原來(lái)的組成的元組還原成原來(lái)的對(duì)象。

4.repr()函數(shù)

repr() 函數(shù)將對(duì)象轉(zhuǎn)化為供解釋器讀取的形式。返回一個(gè)對(duì)象的 string 格式。

image
image

看以看出來(lái)當(dāng)輸入的是”123“,則str()函數(shù)輸出的是123,而repr輸出的是”123“.

str()不保留原來(lái)的類型,而repr則保留數(shù)據(jù)類型。

每天進(jìn)步一點(diǎn)

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容