首页 > 编程语言 > 详细

【Py】Python基础——杂七杂八的用法

时间:2020-06-20 21:33:54      阅读:80      评论:0      收藏:0      [点我收藏+]

迭代器

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:
    

【Py】Python基础——杂七杂八的用法

原文:https://www.cnblogs.com/Ryan16231112/p/13170293.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!