笔记:Python高级语法汇总

  一:列表推导式

num = [1, 4, -5, 10, -7, 2, 3, -1]
filter_and_squared = []

for number in num:
    if number > 0:
        filter_and_squared.append(number ** 2)

print(filter_and_squared)

filter_and_squared1 = [x ** 2 for x in num if x > 0]
print(filter_and_squared1)

  二:上下文管理器

# with open

f = open('../../xx.xx','a')
f.write("hello world")
f.close()

# 用with
with open("../../xx.xx",'a') as f:
    f.write("hello world")

  三:装饰器

import time
from functools import wraps


def timethis(func):
    '''
    Decorator that reports the execution time.
    '''

    @wraps(func)
    def wrapper(*args, **kwargs):
        start = time.time()
        result = func(*args, **kwargs)
        end = time.time()
        print(func.__name__, end - start)
        return result

    return wrapper


@timethis
def countdown(n):
    while n > 0:
        n -= 1


countdown(100000)


# 在python中
@timethis
def countdown(n):


# 等同于:
def countdown(n):
    ...
    countdown = timethis(countdown)

  四:切片

L = ['Michael', 'Sarah', 'Tracy', 'Bob', 'Jack']
print(L[:3])

  五:迭代

d = {'a': 1, 'b': 2, 'c': 3}
for key, value in d:
    print("key:value" % (key, value))

  六:map函数

def f(x):
    return x * x


ret = map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9])
print(ret)

  七:闭包

def lazy_sum(*args):
    def sum():
        ax = 0
        for n in args:
            ax = ax + n
        return ax

    return sum

  

 

转载于:https://www.cnblogs.com/huxiaoyi/p/9858451.html

你可能感兴趣的:(笔记:Python高级语法汇总)