← 返回首页

python进阶用法

📖 正文内容

*args和**kwargs

我观察到,⼤部分新的Python程序员都需要花上⼤量时间理解清楚*args和**kwargs这两个魔法变量。那么它们到底是什么?

⾸先让我告诉你,其实并不是必须写成args和**kwargs。 只有变量前⾯的(星号)才是必须的.你也可以写成var和**vars.⽽写成args和**kwargs只是⼀个通俗的命名约定。 那就让我们先看⼀下*args吧。

*args的⽤法

*args和**kwargs主要⽤于函数定义。 你可以将不定数量的参数传递给⼀个函数。这⾥的不定的意思是:预先并不知道,函数使⽤者会传递多少个参数给你,所以在这个场景下使⽤这两个关键字。*args是⽤来发送⼀个⾮键值对的可变数量的参数列表给⼀个函数
def test_var_args(f_arg, *argv):   print("first normal arg:", f_arg)   for arg in argv:     print("another arg through *argv:", arg)     test_var_args('yasoob', 'python', 'eggs', 'test')
first normal arg: yasoob

another arg through *argv: python

another arg through *argv: eggs

another arg through *argv: test

**kwargs的⽤法

**kwargs允许你将不定长度的键值对,作为参数传递给⼀个函数。 如果你想要在⼀个函数⾥处理带名字的参数,你应该使⽤**kwargs。
def greet_me(**kwargs):   for key, value in kwargs.items():     print("{0} == {1}".format(key, value)) greet_me(name="yasoob")
name == yasoob
现在你可以看出我们怎样在⼀个函数⾥,处理了⼀个键值对参数了。

这就是**kwargs的基础,⽽且你可以看出它有多么管⽤。 接下来让我们谈谈,你怎样使⽤*args和**kwargs来调⽤⼀个参数为列表或者字典的函数。

def test_args_kwargs(arg1, arg2, arg3):   print("arg1:", arg1)   print("arg2:", arg2)   print("arg3:", arg3) args = ("two", 3, 5) test_args_kwargs(*args) -------------------- kwargs = {"arg3": 3, "arg2": "two", "arg1": 5} test_args_kwargs(**kwargs)
arg1: two

arg2: 3

arg3: 5

--------------

arg1: 5

arg2: two

arg3: 3

标准参数与*args、**kwargs在使⽤时的顺序==》some_func(fargs, *args, **kwargs)

生成器

一、什么是生成器?

在python中,使用了yield的函数被称为生成器,生成器返回的是一个迭代器的函数,只能用于迭代操作,在调用生成器运行的过程中,每次遇到yield时函数会暂停并保存当前所有的运行信息,返回yield的值,并在下一次执行next()方法时从当前位置继续运行。

生成器应用实例,利用生成器输出1—1亿的数。

list = (i for i in range(1,100000000)) for item in list:     print(item)

二、如何创建一个生成器?如何使用生成器?

(1)使用函数创建

    1.函数内部需要实现一个循环体,并实现返回值推导算法,并由yield返回每次推导出来的值

    2.yield关键词,其核心作用是

            1.类似return,将指定值或多个值返回给调用方

            2.记录此次返回或遍历的位置,返回数值之后,挂起,直到下一次执行next函数再重新从挂起点接着运行(类似于断点)

def fib(max):     a, b = 1, 1     while a < max:         yield a  # generators return an iterator that returns a stream of values.         a, b = b, a + b for n in fib(15):     print(n)
1
1
2
3
5
8
13
(2)使用生成器推导式

核心点如下:

        1.整体规律,类似类表生成推导式

        2.只是语法,由之前的[ ],变成()

# 使用推导式,对于小于10的,乘3,对于大于等于10的,乘5 # 此时返回的不再是列表,而是一个生成器 g=(i*3 if i<10 else i*5 for i in range(100))
0
3
6
9
12
15
18
21
24
27

三、yield与return对比

1.相同点:

        (1)均在函数体内使用,并且向调用方返回结果

        (2)均可返回一个值或者多个值,如果是多个值,则是以元组格式返回

2.不同点:

       1.包含yield的函数,调用时最终返回的是一个生成器,单纯的return函数,调用时返回的是一         个值。

       2.return执行并返回值后,便会退出函数体,该函数体内存空间即回收释放

       3.yield执行并返回值后,不会退出函数体,而是挂起,待下次next时,再从挂起点恢复运行

       4.yield语句可以接受通过生成器send()方法传入的参数并赋值给一个变量,以动态调整生成器         的行为表现

        5.yield语句的返回值,可以通过from关键词指定返回源

3.return在生成器中的作用:

        1.在一个生成器函数中,如果没有return,则默认执行至函数完毕,如果在执行过程中                     return,则直接抛出StopIteration终止迭代。

#1、yield和return共存 def gene(maxcount):     a,b=0,1     count=1     while True:         if count>maxcount:             #直接退出函数体             return         else:             #返回值后,函数在该处挂起,下次再从该处恢复运行             yield a+b             a,b=b,a+b             count+=1 #2、yield接受通过send传入的参数并动态调整生成器行为 # def gene(maxcount):     a,b=0,1     count=1     while True:         if count>maxcount:             return         else:             msg=yield a+b             if msg=='stop':                 return             a,b=b,a+b             count+=1 g=gene(10) next(g) g.send('msg') #生成器终止,并抛出一个StopIteration异常 #3、通过from关键词,接受另外一个生成器,并通过该生成器返回值 #此处只是做展示,大家知道即可,后续如果有类似场景,可以想起来可以这么搞就行 gene1=(i for i in range(10)) def gene2(gene):     yield from gene g=gene2(gene1)

四、基本应用举例

(1)可控文件读取

def read_file(fpath):     BLOCK_SIZE = 1024     with open(fpath, 'rb') as f:         while True:             block = f.read(BLOCK_SIZE)             if block:                 yield block             else:                 return
(2)协程

       进程、线程和协程的概念:

        1.进程指单独的一个CPU运行程序,可以简单认为一个进程就是一个独立的程序

        2.线程是操作系统能够进行运算调度的最小单位。它被包含在进程中,是进程中的实际运作单位

        3.协程可以认为是同一个线程内运行的代码

        4.进程包含线程,线程包含协程

        5.进程、线程的切换和调度,一般由操作系统自动完成,具体调度和切换机制较为复杂

        6.同一线程下,多个协程的切换是由自己编写的代码进行控制,可以实现个性化的调度和切换需求

        协程的特点:

        1.协程是非抢占式特点:协程也存在着切换,这种切换是由我们用户来控制的。协程主解决的是IO的操作

        2.协程有极高的执行效率:因为子程序切换不是线程切换,而是由程序自身控制,因此,没有线程切换的开销,和多线程比,线程数量越多,协程的性能优势就越明显

        3.协程无需关心多线程锁机制,也无需关心数据共享问题:不需要多线程的锁机制,因为只有一个线程,也不存在同时写变量冲突,在协程中控制共享资源不加锁,只需要判断状态就好了,所以执行效率比多线程高很多

        协程借助生成器实现的基本思路:

        1.因为生成器通过yield,可以挂起,待下次执行时再次从挂起点恢复运行,满足切换和交替运行的特点

        2.因为生成器可以通过send函数,动态的干预指定生成器的功能和表现,为实现多个协程之间协作提供了可能

#让两个函数交替运行 #核心就是把两个正常的函数使用yield变为生成器函数,然后交替使用其next调用即可 def task1(times):     for i in range(times):         print('task1 done the :{} time'.format(i+1))         yield def task2(times):     for i in range(times):         print('task2 done the :{} time'.format(i+1))         yield    gene1=task1(5) gene2=task2(5) for i in range(100):     next(gene1)     next(gene2)

装饰器(Decorators)

Python 装饰器(Decorator)是一种特殊类型的函数,它可以修改或增强其他函数的功能,而不改变其原始代码。装饰器本质上是一个接收函数作为参数并返回新函数的函数。装饰器在Python中被广泛用于实现元编程,即在运行时修改或增强程序的行为。

以下是一个装饰器的基本结构和示例:

def my_decorator(func):     def wrapper(*args, **kwargs):         # 装饰器逻辑         print("Before calling the function.")         result = func(*args, **kwargs)         print("After calling the function.")         return result     return wrapper # 被装饰的函数 def original_function():     print("Hello, world!") # 使用装饰器 original_function = my_decorator(original_function) # 调用被装饰的函数 original_function()
在这个例子中,my_decorator 是装饰器,它接收一个函数 func 作为参数。wrapper 是一个内部函数,它包装了原始函数 func 的调用,并在调用前后添加了额外的逻辑。最后,装饰器返回 wrapper 函数,这个返回的函数替换掉原来的 original_function。

当调用 original_function 时,实际上是调用了 my_decorator 返回的 wrapper 函数,因此在执行 original_function 的代码之前和之后,装饰器的逻辑也会被执行。

在实际使用中,Python还提供了 @ 符号来简化装饰器的使用,如下所示:

@my_decorator def original_function():     print("Hello, world!")
这段代码等同于上面使用装饰器的例子,它将 my_decorator 应用于 original_function。@ 符号使得装饰器的应用更加直观和简洁。

在函数中定义函数

在Python中,可以在一个函数内部定义另一个函数,这种做法称为嵌套函数(Nested Function)。嵌套函数是局部作用域的,只能在包含它的外部函数内部使用。这种设计允许在函数内部创建私有辅助函数,这些辅助函数只对包含它们的函数可见,提高了代码的封装性和可读性。

下面是一个简单的例子,展示如何在函数中定义和使用一个内部函数:

def outer_function():     def inner_function():         print("This is the inner function.")     inner_function()  # 在外部函数中调用内部函数 outer_function()
在这个例子中,inner_function 是在 outer_function 内部定义的,只有 outer_function 可以直接访问 inner_function。当我们调用 outer_function 时,inner_function 会被执行,输出 "This is the inner function."。

请注意,内部函数无法直接访问外部函数的局部变量,除非这些变量是全局变量或者使用 nonlocal 关键字声明。但是,内部函数可以访问外部函数的参数,只要这些参数在内部函数被调用时是可访问的。

def outer_function(name):     def inner_function():         print(f"Inside: {name}")     inner_function() outer_function("Alice")  # 输出: Inside: Alice

各种推导式

Python中的推导式(Comprehensions)是一种简洁、高效的构造新序列的方式,它可以从现有的序列类型(如列表、集合、字典等)中创建新的序列,同时可以附加条件过滤。以下是Python中几种主要的推导式类型及其基本用法:

列表推导式(List Comprehension)

列表推导式是最常用的推导式形式,用于从一个或多个现有列表(或其他可迭代对象)创建一个新的列表。其基本结构是:

[expression for item in iterable if condition]

expression:表示新列表中每个元素的计算方式。

item:表示从iterable中取出的当前项。

iterable:可迭代对象,如列表、元组、字符串等。

condition(可选):用于过滤的条件表达式。

numbers = [1, 2, 3, 4, 5] squares = [n**2 for n in numbers]  # 计算平方 even_squares = [n**2 for n in numbers if n % 2 == 0]  # 计算偶数的平方

集合推导式(Set Comprehension)

集合推导式与列表推导式类似,但结果是一个集合,集合自动去重,语法结构相同,只是使用花括号{}代替方括号[]
{expression for item in iterable if condition}
numbers = [1, 2, 2, 3, 4] unique_squares = {n**2 for n in numbers}  # 计算平方并去重

字典推导式(Dictionary Comprehension)

字典推导式用于创建新的字典,每个键值对都是根据表达式和条件从原序列计算得出的。
{key_expression: value_expression for item in iterable if condition}
names = ['Alice', 'Bob', 'Charlie'] ages = [24, 30, 19] age_dict = {name: age for name, age in zip(names, ages)}  # 根据姓名和年龄创建字典

生成器推导式(Generator Comprehension)

生成器推导式与列表推导式相似,但使用圆括号(),生成器是惰性求值的,更适合处理大数据集。
(expression for item in iterable if condition)
numbers = range(10) even_numbers_gen = (n for n in numbers if n % 2 == 0)  # 生成偶数的生成器

元组推导式(Tuple Comprehension)

虽然Python没有专门的元组推导式,但你可以直接使用列表推导式的语法,然后通过转换为元组来达到类似效果。
tuple((expression for item in iterable if condition))
不过,通常直接使用生成器表达式或列表推导式更常见,然后根据需要转换数据类型。

以上就是Python中几种主要的推导式类型,它们大大增强了代码的简洁性和可读性,是Python编程中的重要工具

lambda表达式

lambda 表达式是 Python 中的一种简短定义匿名函数(function without a name)的方式。这种函数主要用于临时创建一个简单的函数,通常在需要一个短小的函数对象,但又不想为此编写一个完整的 def 函数时使用。lambda 函数的语法如下:
lambda arguments: expression
lambda参数:操作(参数)
其中:

arguments 是逗号分隔的参数列表,可以有零个或多个参数。

expression 是一个单行的表达式,它定义了函数的计算逻辑。

lambda 函数的返回值是表达式的结果,它不能包含复杂的控制流(如 if 语句、for 循环或 try/except 块),也不能包含多行代码。

下面是一些使用 lambda 表达式的例子:

# 计算两数之和 add = lambda x, y: x + y print(add(3, 5))  # 输出: 8 # 排序列表,根据元素长度 words = ['apple', 'banana', 'cherry'] sorted_words = sorted(words, key=lambda word: len(word)) print(sorted_words)  # 输出: ['apple', 'cherry', 'banana'] # 判断是否为偶数 is_even = lambda num: num % 2 == 0 print(is_even(4))  # 输出: True
尽管 lambda 表达式在某些场合下非常有用,但它们不应过度使用,因为它们的可读性不如使用 def 关键字定义的标准函数。在代码中大量使用 lambda 可能会让代码变得难以理解和维护。

💡 示例代码

<div style='--en-codeblock:true;--en-blockId:vfApSur7_z9;--en-meta:{"title":"","lang":"Python","theme":"default","showLine":true,"lineWrap":false};box-sizing: border-box; padding: 8px; font-family: Monaco, Menlo, Consolas, "Courier New", monospace; font-size: 12px; color: rgb(51, 51, 51); border-top-left-radius: 4px; border-top-right-radius: 4px; border-bottom-right-radius: 4px; border-bottom-left-radius: 4px; background-color: rgb(251, 250, 248); border: 1px solid rgba(0, 0, 0, 0.14902); background-position: initial initial; background-repeat: initial initial; margin-top: 6px;'>def test_var_args(f_arg, *argv):
  print("first normal arg:", f_arg)
  for arg in argv:
    print("another arg through *argv:", arg)
    
test_var_args('yasoob', 'python', 'eggs', 'test')</div>

<div style='--en-codeblock:true;--en-blockId:MpuhSSUSYmr;--en-meta:{"title":"","lang":"Python","theme":"default","showLine":true,"lineWrap":false};box-sizing: border-box; padding: 8px; font-family: Monaco, Menlo, Consolas, "Courier New", monospace; font-size: 12px; color: rgb(51, 51, 51); border-top-left-radius: 4px; border-top-right-radius: 4px; border-bottom-right-radius: 4px; border-bottom-left-radius: 4px; background-color: rgb(251, 250, 248); border: 1px solid rgba(0, 0, 0, 0.14902); background-position: initial initial; background-repeat: initial initial; margin-top: 6px;'>def greet_me(**kwargs):
  for key, value in kwargs.items():
    print("{0} == {1}".format(key, value))

greet_me(name="yasoob")</div>

<div style='--en-codeblock:true;--en-blockId:vM2KTmxQT4d;--en-meta:{"title":"","lang":"Python","theme":"default","showLine":true,"lineWrap":false};box-sizing: border-box; padding: 8px; font-family: Monaco, Menlo, Consolas, "Courier New", monospace; font-size: 12px; color: rgb(51, 51, 51); border-top-left-radius: 4px; border-top-right-radius: 4px; border-bottom-right-radius: 4px; border-bottom-left-radius: 4px; background-color: rgb(251, 250, 248); border: 1px solid rgba(0, 0, 0, 0.14902); background-position: initial initial; background-repeat: initial initial; margin-top: 6px;'>def test_args_kwargs(arg1, arg2, arg3):
  print("arg1:", arg1)
  print("arg2:", arg2)
  print("arg3:", arg3)

args = ("two", 3, 5)
test_args_kwargs(*args)
--------------------
kwargs = {"arg3": 3, "arg2": "two", "arg1": 5}
test_args_kwargs(**kwargs)</div>

<div style='--en-codeblock:true;--en-blockId:vIR9QG2EZ4M;--en-meta:{"title":"","lang":"Python","theme":"default","showLine":true,"lineWrap":false};box-sizing: border-box; padding: 8px; font-family: Monaco, Menlo, Consolas, "Courier New", monospace; font-size: 12px; color: rgb(51, 51, 51); border-top-left-radius: 4px; border-top-right-radius: 4px; border-bottom-right-radius: 4px; border-bottom-left-radius: 4px; background-color: rgb(251, 250, 248); border: 1px solid rgba(0, 0, 0, 0.14902); background-position: initial initial; background-repeat: initial initial; margin-top: 6px;'>list = (i for i in range(1,100000000))
for item in list:
    print(item)
 </div>

<div style='--en-codeblock:true;--en-blockId:uX1kTKBednG;--en-meta:{"title":"","lang":"Python","theme":"default","showLine":true,"lineWrap":false};box-sizing: border-box; padding: 8px; font-family: Monaco, Menlo, Consolas, "Courier New", monospace; font-size: 12px; color: rgb(51, 51, 51); border-top-left-radius: 4px; border-top-right-radius: 4px; border-bottom-right-radius: 4px; border-bottom-left-radius: 4px; background-color: rgb(251, 250, 248); border: 1px solid rgba(0, 0, 0, 0.14902); background-position: initial initial; background-repeat: initial initial; margin-top: 6px;'>def fib(max):
    a, b = 1, 1
    while a &lt; max:
        yield a  # generators return an iterator that returns a stream of values.
        a, b = b, a + b
 
 
for n in fib(15):
    print(n)</div>

<div style='--en-codeblock:true;--en-blockId:_wwsTWRw-HM;--en-meta:{"title":"","lang":"Python","theme":"default","showLine":true,"lineWrap":false};box-sizing: border-box; padding: 8px; font-family: Monaco, Menlo, Consolas, "Courier New", monospace; font-size: 12px; color: rgb(51, 51, 51); border-top-left-radius: 4px; border-top-right-radius: 4px; border-bottom-right-radius: 4px; border-bottom-left-radius: 4px; background-color: rgb(251, 250, 248); border: 1px solid rgba(0, 0, 0, 0.14902); background-position: initial initial; background-repeat: initial initial; margin-top: 6px;'># 使用推导式,对于小于10的,乘3,对于大于等于10的,乘5
# 此时返回的不再是列表,而是一个生成器
g=(i*3 if i&lt;10 else i*5 for i in range(100))</div>

<div style='--en-codeblock:true;--en-blockId:aWpkRKP0ssT;--en-meta:{"title":"","lang":"Python","theme":"default","showLine":true,"lineWrap":false};box-sizing: border-box; padding: 8px; font-family: Monaco, Menlo, Consolas, "Courier New", monospace; font-size: 12px; color: rgb(51, 51, 51); border-top-left-radius: 4px; border-top-right-radius: 4px; border-bottom-right-radius: 4px; border-bottom-left-radius: 4px; background-color: rgb(251, 250, 248); border: 1px solid rgba(0, 0, 0, 0.14902); background-position: initial initial; background-repeat: initial initial; margin-top: 6px;'>#1、yield和return共存
def gene(maxcount):
    a,b=0,1
    count=1
    while True:
        if count&gt;maxcount:
            #直接退出函数体
            return 
        else:
            #返回值后,函数在该处挂起,下次再从该处恢复运行
            yield a+b
            a,b=b,a+b
            count+=1
 
#2、yield接受通过send传入的参数并动态调整生成器行为
#
def gene(maxcount):
    a,b=0,1
    count=1
    while True:
        if count&gt;maxcount:
            return 
        else:
            msg=yield a+b
            if msg=='stop':
                return
            a,b=b,a+b
            count+=1
g=gene(10)
next(g)
g.send('msg') #生成器终止,并抛出一个StopIteration异常
 
#3、通过from关键词,接受另外一个生成器,并通过该生成器返回值
#此处只是做展示,大家知道即可,后续如果有类似场景,可以想起来可以这么搞就行
gene1=(i for i in range(10))
def gene2(gene):
    yield from gene
g=gene2(gene1)</div>

<div style='--en-codeblock:true;--en-blockId:YxNjRqIHnIh;--en-meta:{"title":"","lang":"Python","theme":"default","showLine":true,"lineWrap":false};box-sizing: border-box; padding: 8px; font-family: Monaco, Menlo, Consolas, "Courier New", monospace; font-size: 12px; color: rgb(51, 51, 51); border-top-left-radius: 4px; border-top-right-radius: 4px; border-bottom-right-radius: 4px; border-bottom-left-radius: 4px; background-color: rgb(251, 250, 248); border: 1px solid rgba(0, 0, 0, 0.14902); background-position: initial initial; background-repeat: initial initial; margin-top: 6px;'>def read_file(fpath): 
    BLOCK_SIZE = 1024 
    with open(fpath, 'rb') as f: 
        while True: 
            block = f.read(BLOCK_SIZE) 
            if block: 
                yield block 
            else: 
                return</div>

<div style='--en-codeblock:true;--en-blockId:SnDIROPe6u9;--en-meta:{"title":"","lang":"Python","theme":"default","showLine":true,"lineWrap":false};box-sizing: border-box; padding: 8px; font-family: Monaco, Menlo, Consolas, "Courier New", monospace; font-size: 12px; color: rgb(51, 51, 51); border-top-left-radius: 4px; border-top-right-radius: 4px; border-bottom-right-radius: 4px; border-bottom-left-radius: 4px; background-color: rgb(251, 250, 248); border: 1px solid rgba(0, 0, 0, 0.14902); background-position: initial initial; background-repeat: initial initial; margin-top: 6px;'>#让两个函数交替运行
#核心就是把两个正常的函数使用yield变为生成器函数,然后交替使用其next调用即可
def task1(times):
    for i in range(times):
        print('task1 done the :{} time'.format(i+1))
        yield
def task2(times):
    for i in range(times):
        print('task2 done the :{} time'.format(i+1))
        yield    
gene1=task1(5)
gene2=task2(5)
for i in range(100):
    next(gene1)
    next(gene2)</div>

<div style='--en-codeblock:true;--en-blockId:ARn3RCLdlUF;--en-meta:{"title":"","lang":"Python","theme":"default","showLine":true,"lineWrap":false};box-sizing: border-box; padding: 8px; font-family: Monaco, Menlo, Consolas, "Courier New", monospace; font-size: 12px; color: rgb(51, 51, 51); border-top-left-radius: 4px; border-top-right-radius: 4px; border-bottom-right-radius: 4px; border-bottom-left-radius: 4px; background-color: rgb(251, 250, 248); border: 1px solid rgba(0, 0, 0, 0.14902); background-position: initial initial; background-repeat: initial initial; margin-top: 6px;'>def my_decorator(func):
    def wrapper(*args, **kwargs):
        # 装饰器逻辑
        print("Before calling the function.")
        result = func(*args, **kwargs)
        print("After calling the function.")
        return result
    return wrapper

# 被装饰的函数
def original_function():
    print("Hello, world!")

# 使用装饰器
original_function = my_decorator(original_function)

# 调用被装饰的函数
original_function()
</div>

<div style='--en-codeblock:true;--en-blockId:QyNzRusckea;--en-meta:{"title":"","lang":"Python","theme":"default","showLine":true,"lineWrap":false};box-sizing: border-box; padding: 8px; font-family: Monaco, Menlo, Consolas, "Courier New", monospace; font-size: 12px; color: rgb(51, 51, 51); border-top-left-radius: 4px; border-top-right-radius: 4px; border-bottom-right-radius: 4px; border-bottom-left-radius: 4px; background-color: rgb(251, 250, 248); border: 1px solid rgba(0, 0, 0, 0.14902); background-position: initial initial; background-repeat: initial initial; margin-top: 6px;'>@my_decorator
def original_function():
    print("Hello, world!")
</div>

<div style='--en-codeblock:true;--en-blockId:WYvyTeZ9qiJ;--en-meta:{"title":"","lang":"Python","theme":"default","showLine":true,"lineWrap":false};box-sizing: border-box; padding: 8px; font-family: Monaco, Menlo, Consolas, "Courier New", monospace; font-size: 12px; color: rgb(51, 51, 51); border-top-left-radius: 4px; border-top-right-radius: 4px; border-bottom-right-radius: 4px; border-bottom-left-radius: 4px; background-color: rgb(251, 250, 248); border: 1px solid rgba(0, 0, 0, 0.14902); background-position: initial initial; background-repeat: initial initial; margin-top: 6px;'>def outer_function():
    def inner_function():
        print("This is the inner function.")

    inner_function()  # 在外部函数中调用内部函数

outer_function()
</div>

<div style='--en-codeblock:true;--en-blockId:Rg1UTSTOQnS;--en-meta:{"title":"","lang":"Python","theme":"default","showLine":true,"lineWrap":false};box-sizing: border-box; padding: 8px; font-family: Monaco, Menlo, Consolas, "Courier New", monospace; font-size: 12px; color: rgb(51, 51, 51); border-top-left-radius: 4px; border-top-right-radius: 4px; border-bottom-right-radius: 4px; border-bottom-left-radius: 4px; background-color: rgb(251, 250, 248); border: 1px solid rgba(0, 0, 0, 0.14902); background-position: initial initial; background-repeat: initial initial; margin-top: 6px;'>def outer_function(name):
    def inner_function():
        print(f"Inside: {name}")

    inner_function()

outer_function("Alice")  # 输出: Inside: Alice
</div>

<div style='--en-codeblock:true;--en-blockId:uej1R220Zkj;--en-meta:{"title":"","lang":"Python","theme":"default","showLine":true,"lineWrap":false};box-sizing: border-box; padding: 8px; font-family: Monaco, Menlo, Consolas, "Courier New", monospace; font-size: 12px; color: rgb(51, 51, 51); border-top-left-radius: 4px; border-top-right-radius: 4px; border-bottom-right-radius: 4px; border-bottom-left-radius: 4px; background-color: rgb(251, 250, 248); border: 1px solid rgba(0, 0, 0, 0.14902); background-position: initial initial; background-repeat: initial initial; margin-top: 6px;'>numbers = [1, 2, 3, 4, 5]
squares = [n**2 for n in numbers]  # 计算平方
even_squares = [n**2 for n in numbers if n % 2 == 0]  # 计算偶数的平方
</div>

<div style='--en-codeblock:true;--en-blockId:WLlNTyqidHE;--en-meta:{"title":"","lang":"Python","theme":"default","showLine":true,"lineWrap":false};box-sizing: border-box; padding: 8px; font-family: Monaco, Menlo, Consolas, "Courier New", monospace; font-size: 12px; color: rgb(51, 51, 51); border-top-left-radius: 4px; border-top-right-radius: 4px; border-bottom-right-radius: 4px; border-bottom-left-radius: 4px; background-color: rgb(251, 250, 248); border: 1px solid rgba(0, 0, 0, 0.14902); background-position: initial initial; background-repeat: initial initial; margin-top: 6px;'>numbers = [1, 2, 2, 3, 4]
unique_squares = {n**2 for n in numbers}  # 计算平方并去重
</div>

<div style='--en-codeblock:true;--en-blockId:oyAZRC7MFyt;--en-meta:{"title":"","lang":"Python","theme":"default","showLine":true,"lineWrap":false};box-sizing: border-box; padding: 8px; font-family: Monaco, Menlo, Consolas, "Courier New", monospace; font-size: 12px; color: rgb(51, 51, 51); border-top-left-radius: 4px; border-top-right-radius: 4px; border-bottom-right-radius: 4px; border-bottom-left-radius: 4px; background-color: rgb(251, 250, 248); border: 1px solid rgba(0, 0, 0, 0.14902); background-position: initial initial; background-repeat: initial initial; margin-top: 6px;'>names = ['Alice', 'Bob', 'Charlie']
ages = [24, 30, 19]
age_dict = {name: age for name, age in zip(names, ages)}  # 根据姓名和年龄创建字典
</div>

<div style='--en-codeblock:true;--en-blockId:0-SybtWKg;--en-meta:{"title":"","lang":"Python","theme":"default","showLine":true,"lineWrap":false};box-sizing: border-box; padding: 8px; font-family: Monaco, Menlo, Consolas, "Courier New", monospace; font-size: 12px; color: rgb(51, 51, 51); border-top-left-radius: 4px; border-top-right-radius: 4px; border-bottom-right-radius: 4px; border-bottom-left-radius: 4px; background-color: rgb(251, 250, 248); border: 1px solid rgba(0, 0, 0, 0.14902); background-position: initial initial; background-repeat: initial initial; margin-top: 6px;'>numbers = range(10)
even_numbers_gen = (n for n in numbers if n % 2 == 0)  # 生成偶数的生成器
</div>

<div style='--en-codeblock:true;--en-blockId:oBm8TqjvAQY;--en-meta:{"title":"","lang":"Python","theme":"default","showLine":true,"lineWrap":false};box-sizing: border-box; padding: 8px; font-family: Monaco, Menlo, Consolas, "Courier New", monospace; font-size: 12px; color: rgb(51, 51, 51); border-top-left-radius: 4px; border-top-right-radius: 4px; border-bottom-right-radius: 4px; border-bottom-left-radius: 4px; background-color: rgb(251, 250, 248); border: 1px solid rgba(0, 0, 0, 0.14902); background-position: initial initial; background-repeat: initial initial; margin-top: 6px;'># 计算两数之和
add = lambda x, y: x + y
print(add(3, 5))  # 输出: 8

# 排序列表,根据元素长度
words = ['apple', 'banana', 'cherry']
sorted_words = sorted(words, key=lambda word: len(word))
print(sorted_words)  # 输出: ['apple', 'cherry', 'banana']

# 判断是否为偶数
is_even = lambda num: num % 2 == 0
print(is_even(4))  # 输出: True
</div>

💭 技巧提示

💡

📚 参考资料

💬 评论交流

👤
用户 A 2026-03-25

这个技巧很实用,感谢分享!