Python Advanced Usage

Python Advanced Usage

A triplet of expressions

x = 10
y = 20
print(x if x > y else y)
x = 100
y = 20
print(x if x > y else y)

20

100

List comprehensions

print([i for i in range(10)])
print([i*2 for i in range(10)])
print([i-1 for i in range(10)])

Dictionary Builder

zip () Returns a zip object whose internal element is a tuple; or can be converted to a list of tuples

keys = ['name', 'age', 'gender']
values = ['nick', 19, 'male']
res = zip(keys, values)
print(res)
for i in res:
    print(i)
print(F"zip(keys,values): {zip(keys,values)}")

info_dict = {k: v for k, v in res}
print(f"info_dict: {info_dict}")

<zip object at 0x000001D6D7870E08>
('name', 'nick')
('age', 19)
('gender', 'male')
zip(keys,values): <zip object at 0x000001D6D7870E88>
info_dict: {}

Anonymous function

Anonymous function is a function object no variable name

res = (lambda x, y: x+y)(1, 2)
print(res)
print(lambda x, y: x+y)

3
<function at 0x000001958A013E18>

Application (and built-in functions typically associated with)

Generally anonymous functions max (), sorted (), filter (), sorted () method in combination.

For example filter Anonymous

name_list = ['nick', 'jason sb', 'tank sb', 'sean sb']

filter_res = filter(lambda name: name.endswith('sb'), name_list)
print(f"list(filter_res): {list(filter_res)}")

list(filter_res): ['jason sb', 'tank sb', 'sean sb']

Normal function

name_list = ['nick', 'jason sb', 'tank sb', 'sean sb']
def zx(name):
    return name.endswith('sb')

filter_res = filter(zx, name_list)
print(f"list(filter_res): {list(filter_res)}")

list(filter_res): ['jason sb', 'tank sb', 'sean sb']

Guess you like

Origin www.cnblogs.com/zx125/p/11348838.html