メモ:Python上級文法まとめ

1791 ワード

一:リスト導出式
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