<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 < 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<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>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)</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>
💬 评论交流
这个技巧很实用,感谢分享!