天天看點

python内置高階函數_python 中的内置進階函數

1.map(function,iterable)

map是把疊代對象依次進行函數運算,并傳回。

例子:

python内置高階函數_python 中的内置進階函數

map傳回的十分map對象,需要list()函數轉化。

2.exec()函數

執行儲存在字元串或檔案中的 Python 語句,相比于 eval,exec可以執行更複雜的 Python 代碼。

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

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.

全局變量必須是一個字典類型,局部變量可以是任何映射

If only globals is given, locals defaults to it.

如果僅僅給訂全局變量,局部變量也預設是它。

# 執行單行語句

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

# 執行多行語句

exec("""

for i in range(10):

print(i,end=",")

""")

運作結果

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 函數内空間變量

# G->global 全局變量

# B-> bulltlins

# 局部變量———閉包空間———全局變量———内模組化塊

func()

結果是:

60

x= 10 ,y= 20,z= 30

33

x= 1 ,y= 2, z= 30

34

x= 1 ,y= 3 ,z= 30

python 中尋找變量順序:

LEGB

L-Local

E->enclose function local

G->global

B->bultins

局部變量->函數體内變量-》全局變量-》内置函數

3.zip()函數

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)

結果:

(1,'a')

(2,'b')

(3,'c')

python内置高階函數_python 中的内置進階函數
python内置高階函數_python 中的内置進階函數

zip将可疊代對象作為參數,将對象中對應的元素打包組成一個個元組,然後傳回這些元組組成的清單。

而zip(*c)則是将原來的組成的元組還原成原來的對象。

4.repr()函數

repr() 函數将對象轉化為供解釋器讀取的形式。傳回一個對象的 string 格式。

python内置高階函數_python 中的内置進階函數
python内置高階函數_python 中的内置進階函數

看以看出來當輸入的是”123“,則str()函數輸出的是123,而repr輸出的是”123“.

str()不保留原來的類型,而repr則保留資料類型。