Some built-in functions of python

Keywords: Python Lambda less Pycharm

Built in function mind map: https://www.processon.com/mindmap/5c10ca52e4b0c2ee256ac034

Built-in function

Anonymous function

The unified name of anonymous function is: < lambda >

Usage scenario: used with sorted, map and filter

 

fn = lambda a, b : a + b # Define a very simple function. Do not use complex functions lambda
ret = fn(3, 5)
print(ret)
print(fn)

 

sorted. Let you define the sorting rules by yourself

Execution process:

Take each item out of the iteratable object and pass it to the key function as a parameter

Function to return numbers. Sorting by numbers

 

lst = [11,5,36,1,27,58]
s = sorted(lst) # Sort from small to large by default.
print(s)
lst1 = ["Hu Yi Fei", "Zhang Wei", "Guan Gu magic", "Zeng Xiaoxian, LV Xiaobu", "Nuo LAN"]
def func(s):
    return len(s) # Return length
s = sorted(lst, key=func)
print(s)
#Using anonymous functions with sorted Use
#print(sorted(lst, key=lambda s:len(s) ))

 

 

 

filter

Open the iteratable object. Pass the internal elements one by one to the previous function. It is up to this function to decide whether to keep this item or not

 

lst = ["Zhang Wuji", "Zhang Cu Shan", "Fan Bingbing", "Golden King", "Li Bingbing"]
# Filter out Zhang
f = filter(lambda name : not name.startswith("Zhang"), lst)
print("__iter__" in dir(f)) # Iteratable object
for el in f:
    print(el)

lst = [
    {"name":"alex", "shengao":150, "tizhong":250},
    {"name":"wusir", "shengao":158, "tizhong":150},
    {"name":"taibai", "shengao":177, "tizhong":130},
    {"name":"ritian", "shengao":165, "tizhong":130},
    {"name":"nvshen", "shengao":160, "tizhong":120},
    {"name":"baolang", "shengao":183, "tizhong":190}
]
# Filter out people who weigh more than 180 and want less than 180
f = filter(lambda d : d['tizhong'] <= 180, lst)
print(list(f))

 

 

Map map function

lst = ["Basketball ball", "Playing billiards", "Sing", "Crawling mountain", "step"]
m = map(lambda s: "hobby:"+s , lst)
print(list(m))
lst = [1,5,78,12,16] # Calculate the square of each number
print([i **2 for i in lst])
m = map(lambda i: i ** 2, lst)
print(list(m))

eval is to execute data of string type as code

s = "18+2"
ret = eval(s) # Execute code of string type
print(ret)
s = "{'name':'alex', 'age':18, 'isMan':False}" # Character string
ret = eval(s)  # Focus on return value
print(ret)
print(type(ret))
exec execute executes code of string type, which cannot be too long or too messy

 

code = input("Please enter the code you want to execute")
exec(code) # no return value. To return a value eval
print(a)   # pycharm Error reporting may not be accurate

 

compile: precompile the code you want to execute first. We can execute our code through exec and eval
code = '''
for i in range(10):
    if i % 2 == 0:
        print(i)
'''
c = compile(code, "", "exec") # Preload code
exec(c) # Run code

Posted by jimbob on Thu, 05 Dec 2019 01:16:29 -0800