【Py】Python基础——杂七杂八的用法
作者:互联网
迭代器
list1=[1,2]
it = iter(list1)
print(next(it)) # 1
print(next(it)) # 2
print(next(it)) #StopIteration异常
生成器
def frange(start, end, step):
x = start
while x<stop:
yield x # 运行到这里会暂停并记录x值,调用next时返回这个值
x += step
for i in frange(10, 20, 0.5):
print(i)#10 10.5 11...
lambda表达式
def true():return True
lambda : True
# lambda [传入参数]: [返回结果]
lambda x, y : x+y
内建函数
filter()
a = [1, 2, 3, 4]
list(filter(lambda x : x>2, a))# 返回3,4
# filter([筛选函数],[筛选的可迭代的东西])
map()
a=[1,2,3]
b =[2,3,4]
list(map(lambda x,y : x+y), a, b)#3,5,7
reduce()
a=[2,3,4]
from functools import reduce
reduce(lambda x,y : x+y, a, 1)#10(((1+2)+3)+4)
闭包
def sum(a):
def add(b):
return a+b
return add
num1 = sum(2)
num2 = num1(2)
装饰器
def new_timer(argv):
def timer(func):
def wrapper():
start_time=time.time()
func()
stop_time=time.time()
print(stop_time-start_time)
print(argv, func.__name__)
return wrapper
return timer
@new_timer('sleep2') # 语法糖
def sleep_2():
time.sleep(2)
sleep_2() # 2.00000s,sleep2, sleep_2
异常处理
try:
except:
finally:
标签:return,Python,Py,杂七杂八,sleep,time,print,def,lambda 来源: https://www.cnblogs.com/Ryan16231112/p/13170293.html