Lambda
-
map(function, iterable):将指定的函数应用在列表的每个元素上,并返回一个新的序列list1 = (1,2,3) xxx= map(lambda x: x**2, list1) # 算每个元素的平方 print(list(xxx)) # [1, 4, 9] -
filter(function, iterable):将指定的函数应用在列表的每个元素上,并返回一个新的序列numbers = [1, 2, 3, 4] xxx= filter(lambda x : x%2 ==0 ,numbers) # 过滤出为True的元素 print(list(xxx))
推导式
-
列表推导式
result = [x for x in list1 if x not in set(list2)] # 在list1中但不在list2中的元素 names = ['Bob','Tom','alice','Jerry','Wendy','Smith'] new_names = [name.upper() for name in names if len(name)>3] # 找到名字长度大于3的,并转为大写 -
元组推导式
a = (x for x in range(1,3)) tuple(a)
多线程
import threading
import time
def task(thread_name, delay):
print(f"Thread {thread_name} is starting...")
time.sleep(delay)
print(f"Thread {thread_name} is finished.")
if __name__ == '__main__':
# 创建线程
threads = []
for i in range(5):
thread = threading.Thread(target=task, args=(f"Thread-{i}", i)) # args为传参
threads.append(thread)
thread.start()
# 等待所有线程结束
for thread in threads:
thread.join()
print("All threads have finished.")
装饰器
from functools import wraps
def logger(func):
@wraps(func)
def decorated(*args, **kwargs):
return func(*args, **kwargs)
return decorated
@logger
def addition_func(x):
return x + x
print(addition_func(4)) # 输出8