python3控制结构、函数、迭代器、生成器、列表推导式、lambda表达式

控制结构

条件判断

n = 10
i = 2
if n == i:
    print("equal")
elif n < i:
    print("lower")
else:
    print("higher")
    
score = 89
match score:
    case 100:
        print("level A+")
    case x if x < 100 and x > 90:
        print("level A")
    case 85 | 87 | 88 | 89 | 90:
        print("level A-")
    case x if x < 85 and x > 60:
        print("level B")
    case _:  # _表示匹配到其他任何情况
        print("level C")

循环遍历

while i < n:
    i += 1
    if i % 2 == 0:
        continue
    print(i)
else:
    print("done")


for i in range(0, 5):
    if i > 3:
        break
    print(i)
else:
    pass

lst = ["aa", "bb"]
for name in lst:
    print(name)

tp = ("aa", "bb")
for name in tp:
    print(name)

dct = {"name": "lily", "age": 19}
for key, value in dct.items():
    print(key, value)
for key in dct.keys():
    print(key)
for value in dct.values():
    print(value)
for key in dct:
    print(key, dct[key])

函数

参数传递方式

# 参数传递分为值传递和引用传递,函数可以以tuple的形式返回多个值
def test(param_name, param_age, param_fun):
    "函数说明"

    print("inside before", param_name, param_age, param_fun)

    param_name = "b"
    param_age = 2
    param_fun.append("ccc")
    print("inside changed", param_name, param_age, param_fun)

    return param_name, param_age


print(test.__doc__)
name = "a"
age = 1
fun = ["aaa", "bbb"]
res = test(name, age, fun)
print(res)
print("outside", name, age, fun)

输出

函数说明
inside before a 1 ['aaa', 'bbb']
inside changed b 2 ['aaa', 'bbb', 'ccc']
('b', 2)
outside a 1 ['aaa', 'bbb', 'ccc']

内部函数和作用域

# 定义在函数内部的变量拥有一个局部作用域,定义在函数外的拥有全局作用域。
# 局部变量只能在其被声明的函数内部访问,而全局变量可以在整个程序范围内访问。
# 内部函数:函数体内可以再定义函数
def out_func():
    print("out_func", name, age, fun)

    out_func_var = "a"

    def inner_func():
        inner_func_var = "b"

        print("inner_func", name, age, fun)
        print("out_func_var", out_func_var)
        print("inner_func_var", inner_func_var)

    inner_func()


out_func()

输出

out_func a 1 ['aaa', 'bbb', 'ccc']
inner_func a 1 ['aaa', 'bbb', 'ccc']
out_func_var a
inner_func_var b

函数参数 

# 位置参数、默认参数
def test(name, age=18):
    print(name, age)


test("aa", 15)  # aa 15
test("bb")  # bb 18


# 可变长度参数,加了*的参数名会接收除位置参数外的所有未命名参数,加了**的参数名会接收除位置参数外的所有的命名参数
# 若可变长度参数放其它参数后面,传值时其它参数可以不指定参数名
def test(param, *args, **args1):
    print(param, args, args1)


test("aa", 1, 2, 3, name="aa", age=18)  # aa (1, 2, 3) {'name': 'aa', 'age': 18}
nums = [1, 2, 3]
dct = {"name": "lily", "age": 19}
test("aa", *nums)  # aa (1, 2, 3) {}
test(*nums, **dct)  # 1 (2, 3) {'name': 'lily', 'age': 19}
dct = {"name": "bb", "age": 20}
test("aa", *nums, **dct)  # aa (1, 2, 3) {'name': 'bb', 'age': 20}


# 若可变长度参数放其它参数前面,传值时其它参数要指定参数名
def test(*args, param):
    print(param, args)


test(4, 5, param="bb")  # bb (4, 5)
nums = [4, 5]
test(*nums, param="bb")  # bb (4, 5)


# 限制传值使用命名参数,参数列表*以后的必需使用命名参数传值
def test(name, age, *, grade):
    print(name, age, grade)


test("aa", 15, grade="s3")  # aa 15 s3

 常用高阶函数

from functools import reduce

# lambda 函数 -----------------------------
add = lambda a, b, c: a + b + c
print(add(1, 2, 3))  # 6


# sorted 函数 -----------------------------
a_l = [1, 3, 5, 7, 0, -1, -9, -4, -5, 8]
print(sorted(a_l))  # [-9, -5, -4, -1, 0, 1, 3, 5, 7, 8]
print(sorted(a_l, reverse=True))  # [8, 7, 5, 3, 1, 0, -1, -4, -5, -9]

# 字典按照value的顺序排序
colors_d = {"red": 2, "yellow": 4, "green": 1, "black": 3}
print(dict(sorted(colors_d.items(), key=lambda item: item[1])))  # {'green': 1, 'red': 2, 'black': 3, 'yellow': 4}

# 字典按照key的顺序排序
print(dict(sorted(colors_d.items(), key=lambda item: item[0])))  # {'black': 3, 'green': 1, 'red': 2, 'yellow': 4}


# map 函数 --------------------------------
def makeupper(word):
    return word.upper()


colors = ["red", "yellow", "green", "black"]
colors_upper = list(map(makeupper, colors))
print(colors_upper)  # ['RED', 'YELLOW', 'GREEN', 'BLACK']

print(list(map(lambda x: x.upper(), colors)))  # ['RED', 'YELLOW', 'GREEN', 'BLACK']

a = [1, 3, 5]
b = [2, 4, 6]
print(list(map(lambda x, y: x + y, a, b)))  # [3, 7, 11]


# reduce函数 --------------------------------
def add(*args):
    result = 0
    for i in args:
        result += i
    return result


L = list(range(1, 101))
print(reduce(add, L))  # 5050

print(reduce(lambda x, y: x + y, L))  # 5050


# filter函数  --------------------------------
# filter()函数用于过滤序列,过滤掉不符合条件的元素,返回由符合条件元素组成的新序列


def great_then_0(x):
    return x > 0


print(list(filter(great_then_0, a_l)))  # [1, 3, 5, 7, 8]

print(list(filter(lambda x: x > 0, a)))  # [1, 3, 5, 7, 8]

print(dict(filter(lambda x: x[1] > 3, colors_d.items())))  # {'yellow': 4}


# enumerate函数 --------------------------------
# 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在for循环当中
result = enumerate(colors)
for i, j in result:
    print(i, j)  # 0 red 1 yellow  ...


# zip函数
# zip()函数用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的列表
colors = ["red", "yellow", "green", "black"]
fruits = ["apple", "pineapple", "grapes", "cherry"]
for item in zip(colors, fruits):
    print(item)  # ('red', 'apple')  ('yellow', 'pineapple') ...

print(dict(zip(colors, fruits)))  # {'red': 'apple', 'yellow': 'pineapple', 'green': 'grapes', 'black': 'cherry'}

闭包

# 闭包
def funca(x):
    def funcb(y):
        return x + y

    return funcb


func1 = funca(1)
print(func1(2))  # 3

匿名函数

# 匿名函数:使用 lambda 表达式来创建匿名函数
sum1 = lambda x, y: x + y
print(sum1(1, 2))  # 3

装饰器

动态增加函数的功能
# 装饰器:动态增加函数的功能
# 不带参数的装饰器
def write_log(func):
    def wrapper(param):
        func(param)
        print("write log")

    return wrapper


@write_log
def add_order(param):
    print("add_order")
    print(param)


add_order(1)

输出

add_order
1
write log
# 带参数的装饰器
def write_log_bytype(level):
    def write_log(func):
        def wrapper(param):
            func(param)
            print("write {} log".format(level))

        return wrapper

    return write_log


@write_log_bytype("info")
def add_order(param):
    print("add_order")
    print(param)


add_order(1)

输出

add_order
1
write info log

迭代器

from collections.abc import Iterable, Iterator

# 迭代的概念:上一次输出的结果为下一次输入的初始值,重复的过程称为迭代,每次重复即一次迭代,并且每次迭代的结果是下一次迭代的初始值
# 循环是重复不是迭代

# 可迭代的对象:内置__iter__方法的,都是可迭代的对象。list、set、dict
# 迭代器:可迭代对象执行__iter__方法,得到的结果就是迭代器,迭代器对象有__next__方法
# 迭代器对象是一个带状态的对象,调用next()方法的时候返回容器中的下一个值,任何实现了__iter__和__next__()方法的对象都是迭代器,__iter__返回迭代器自身,__next__返回容器中的下一个值,如果容器中没有更多元素了,则抛出StopIteration异常
# 迭代器提供了一种不依赖下标的迭代方式,更节省内存, 无法获取迭代器对象的长度, 不如序列类型取值灵活,只能往后取值,不能往前退

# 判断是否为可迭代对象
print(isinstance("abc", Iterable))  # True
print(isinstance([], Iterable))  # True
print(isinstance((), Iterable))  # True
print(isinstance({"a": 1}, Iterable))  # True
print(isinstance({1, 2}, Iterable))  # True
print(isinstance(open("../files/test.txt", "r"), Iterable))  # True

# 判断是否为迭代器
print(isinstance("abc", Iterator))  # False
print(isinstance([], Iterator))  # False
print(isinstance((), Iterator))  # False
print(isinstance({"a": 1}, Iterator))  # False
print(isinstance({1, 2}, Iterator))  # False
print(isinstance(open("../files/test.txt", "r"), Iterator))  # False

# 迭代器取值
for line in open("../files/test.txt"):
    # print(line)
    pass

 生成器 

# 生成器(generator)是一个特殊的迭代器。yield是生成器实现__next__()方法的关键
# yield是生成器执行的暂停恢复点,函数执行到yield语句会中断并返回,下次执行时从yield的下一个语句继续执行。


def counter(n):
    print("start...")
    i = 0
    while i < n:
        yield i
        i += 1
    print("end...")


g = counter(3)  # 未执行任何counter代码

print(next(g))
print(list(g))

# for i in g:
#     print(i)

输出 

start...
0
end...
[1, 2]

 模拟大文件读取

def read_file(file):
    block_size = 64
    with open(file, "r") as f:
        block = f.read(block_size)
        while block:
            yield block
            block = f.read(block_size)
        else:
            return


fl = read_file("../files/test.txt")
for i in fl:
    print(i)
send方法可以往生成器里的变量传值
def print_num():
    print("begin")
    num = yield
    print("send:", num)
    yield num


p = print_num()
print(p.send(None))  # 必需,初始化
print(p.send(2))  # send方法可以往生成器里的变量传值

输出

begin
None
send: 2
2

生成器表达式

# 生成器表达式是列表推导式的生成器版本
a = list(x for x in range(10) if x % 2 == 0)
print(a)  # [0, 2, 4, 6, 8]

列表推导式

data = [5, 2, -3, 14, 9, 10]
list1 = [x for x in data if x > 5]
list2 = [x**2 for x in data if x > 5]
list3 = [x**2 if x > 5 else x for x in data]
num = 5
list4 = [x for x in range(0, 5)] if num > 5 else [x for x in range(5, 10)]
print(list1)  # [14, 9, 10]
print(list2)  # [196, 81, 100]
print(list3)  # [5, 2, -3, 196, 81, 100]
print(list4)  # [5, 6, 7, 8, 9]

dict1 = {x: x for x in range(0, 5)}
print(dict1)  # {0: 0, 1: 1, 2: 2, 3: 3, 4: 4}

set1 = {x for x in range(0, 5)}
print(set1)  # {0, 1, 2, 3, 4}

str1 = "abc"
list1 = [s for s in str1]
print(list1)  # ['a', 'b', 'c']

data1 = ["Aa", "Bbc", "Cd", "D", "e", "f"]
list1 = [s.upper() for s in data1]
print(list1)  # [14, 9, 10]

matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9],
]
list1 = [j for i in matrix for j in i]
print(list1)  # [1, 2, 3, 4, 5, 6, 7, 8, 9]

data2 = [{"lily": 5}, {"rose": 13}]
list1 = ["{}:{}".format(key, value) for row in data2 for key, value in row.items()]
list2 = [[value for key, value in row.items()] for row in data2]
print(list1)  # ['lily:5', 'rose:13']
print(list2)  # [[5], [13]]

lambda表达式 

from functools import reduce

# lambda表达式
list1 = list(filter(lambda x: x > 5, data))
print(list1)  # [14, 9, 10]
list2 = list(map(lambda x: x * 2, data))
print(list2)  # 输出:[10, 4, -6, 28, 18, 20]
list3 = reduce(lambda x, y: x + y, data)
print(list3)  # 37

# filter函数
res = list(filter(lambda x: x > 5, data))
print(res)  # [14, 9, 10]
res = list(filter(None, [1, 0, False, True]))
print(res)  # [1, True]

  

posted @ 2024-01-10 16:46  carol2014  阅读(3)  评论(0编辑  收藏  举报