#python

python grammar

developer

Python 语法糖

解包 *

一个星号解开数组

# 更清晰的参数
args = [10, 20, 30]
my_function(*args)  # 等价于 my_function(10, 20, 30)

# 列表合并
list1 = [1, 2, 3]
list2 = [4, 5, 6]
combined = [*list1, *list2]  # [1, 2, 3, 4, 5, 6]

# 赋值
first, *middle, last = [1, 2, 3, 4, 5]
print(first)   # 1
print(middle)  # [2, 3, 4]
print(last)    # 5

# 收集列表中多余的值
a, b, *c = [1, 2, 3, 4] # c = [3, 4]

还可以和函数调用组合起来用

async def main():
    # 并发发起请求
    print("=== 开始并发请求 ===")
    data_list = await asyncio.gather(
        fetch_data("用户信息", 2),
        fetch_data("订单列表", 1),
        fetch_data("商品详情", 1.5)
    )
    
    print("\n=== 开始处理数据 ===")
    # 并发处理所有数据
    results = await asyncio.gather(
        *[process_data(data) for data in data_list]
    )

两个星号解开字典

# 传参
params = {'x':1, 'y':2}
myprint(**params)

# 合并字典
dict1 = {"a": 1, "b": 2}
dict2 = {"c": 3, "d": 4}
combined_dict = {**dict1, **dict2}  # {"a": 1, "b": 2, "c": 3, "d": 4}

上下文管理 with as

with as可以自动垃圾回收