lambda表达式基本用法:
z = lambda x, y : x + y
a = z(1, 2)
b = z("x", "y")
print(a)
print(type(a))
print(b)
print(type(b))
运行结果:
3
<class 'int'>
xy
<class 'str'>
三元运算符基本用法:
x = "asd" if 0 else "dsa"
y = "asd" if 1 else "dsa"
print(x)
print(y)
运行结果:
dsa
asd
迭代基本用法:
x = "abcd"
def xxx():
for i in x:
yield i
[print(i, end=" ") for i in xxx()]
运行结果:
a b c d
闭包的基本用法:
x = [1, 2, 3, 4, 5, 6, 7]
def aaa(x):
def bbb():
y = 0
for i in x:
y += i
return y
return bbb
print(aaa(x)())
b_1 = aaa(x)
b_2 = aaa(x)
print(b_1==b_2)
c_1 = aaa(x)()
c_2 = aaa(x)()
print(c_1==c_2)
print()
def bbb(x):
y = []
for i in x:
def aaa():
return i ** 2
y.append(aaa)
return y
print([i() for i in bbb(x)])
print()
def ccc(x):
def aaa(x):
def bbb():
return x ** 2
return bbb
y = []
[y.append(aaa(i)) for i in x]
return y
print([i() for i in ccc(x)])
运行结果:
28
False
True
[49, 49, 49, 49, 49, 49, 49]
[1, 4, 9, 16, 25, 36, 49]
map(), reduce(), filter() 的基本用法:
x = [1, 2, 3, 4, 5, 6, 7]
def aaa(a):
return a * a
print(list(map(aaa, x))) # 每次执行aaa(x[i]),生成迭代返回。
import functools
def bbb(b_1, b_2):
return b_1 + b_2
print(functools.reduce(bbb, x)) # 执行bbb(bbb(bbb(x[0], x[1]), x[2]), x[3])……,直到x[-1],返回结果。
def ccc(c):
return c % 2 == 1
print(list(filter(ccc, x))) # 判断是否为True,如果为True,生成迭代返回。
运行结果:
[1, 4, 9, 16, 25, 36, 49]
28
[1, 3, 5, 7]