Python语法糖大全

本文汇集了一些常用的Python语法糖,供大家查询使用。

1. 集合与序列操作

  • 列表推导式 :创建列表。

    python 复制代码
    [x**2 for x in range(10)]
  • 字典推导式 :创建字典。

    python 复制代码
    {x: x**2 for x in range(10)}
  • 集合推导式 :创建集合。

    python 复制代码
    {x**2 for x in range(10)}
  • 条件列表推导 :在列表推导中使用条件表达式。

    python 复制代码
    [x for x in range(10) if x % 2 == 0]
  • 条件字典推导 :在字典推导中使用条件表达式。

    python 复制代码
    {x: x**2 for x in range(10) if x % 2 != 0}
  • 生成器表达式 :创建迭代器。

    python 复制代码
    (x**2 for x in range(10))
  • 字符串字面量 :单引号或双引号表示的字符串。

    python 复制代码
    s = "This is a string in double quotes."
  • 原始字符串 :使用 r 前缀表示,忽略转义字符。

    python 复制代码
    raw_str = r"New line is represented as \n"
  • 多行字符串 :使用三个引号表示。

    python 复制代码
    multi_line_str = """This is a multi-line
                       string with two lines."""

2. 赋值与解包

  • 多重赋值 :一次性赋值多个变量。

    python 复制代码
    a, b = 1, 2
  • 扩展的可迭代解包 :函数调用中解包可迭代对象。

    python 复制代码
    *a, b = [1, 2, 3, 4]
  • 解包赋值 :从序列中解包值赋给多个变量。

    python 复制代码
    a, *b, c = [0, 1, 2, 3, 4]

3. 函数与Lambda

  • 装饰器 :修改函数或方法的行为。

    python 复制代码
    @my_decorator
    def say_hello():
        print("Hello!")
  • lambda 函数 :创建匿名函数。

    python 复制代码
    add = lambda x, y: x + y
  • 关键字参数 :使用 **kwargs 接受任意数量的关键字参数。

    python 复制代码
    def print_kwargs(**kwargs):
        for key, value in kwargs.items():
            print(f"{key}: {value}")

4. 控制流

  • 条件表达式 :一行 if-else 逻辑。

    python 复制代码
    max_value = a if a > b else b
  • 异常处理 :使用 try...except 语句处理错误。

    python 复制代码
    try:
        x = int(input("Please enter a number: "))
    except ValueError:
        print("That's not a valid number!")
  • 断言 :调试目的的检查。

    python 复制代码
    assert x == y, "x does not equal y"

5. 上下文管理

  • with 语句 :资源管理。

    python 复制代码
    with open('file.txt') as f:
        content = f.read()

6. 类和对象

  • 属性装饰器 :创建管理对象属性的方法。

    python 复制代码
    class MyClass:
        @property
        def value(self):
            return self._value
        @value.setter
        def value(self, new_value):
            self._value = new_value
  • 命名元组 :创建带有命名字段的元组子类。

    python 复制代码
    from collections import namedtuple
    Point = namedtuple('Point', ['x', 'y'])

7. 模块和包

  • 相对与绝对导入 :模块的相对或绝对导入。

    python 复制代码
    from . import my_module  # 相对导入
    from mypackage import my_module  # 绝对导入

8. 类型提示

  • 类型注解 :指定变量的预期类型。

    python 复制代码
    def get_addition_result(a: int, b: int) -> int:
        return a + b

9. 异步编程

  • 异步函数 :使用 asyncawait 编写异步代码。
python 复制代码
import asyncio

# 定义一个异步函数,模拟异步数据获取
async def fetch_data():
    # 模拟异步操作,例如网络请求
    await asyncio.sleep(1)
    return {"data": 1}

# 定义主协程,调用异步函数并打印结果
async def main():
    data = await fetch_data()
    print(data)

# 使用 asyncio.run() 运行主协程,适用于 Python 3.7 及以上版本
asyncio.run(main())

10. 其他

  • 表达式末尾的逗号 :在表达式末尾使用逗号,方便添加或删除元素。

    python 复制代码
    my_list = [1, 2, 3, ]
  • 星号参数和双星号参数 :在函数定义中收集任意数量的参数。

    python 复制代码
    def func(*args, **kwargs):
        print(args, kwargs)
  • 异常的 as 用法 :捕获异常的实例。

    python 复制代码
    try:
        1 / 0
    except ZeroDivisionError as e:
        print(f"Caught an exception: {e}")
  • 海象运算符 :在表达式中进行赋值(Python 3.8+)。

    python 复制代码
    # Python 3.8+
    (element) = [1, 2, 3]
  • 使用 __slots__ :限制实例属性,优化内存使用。

    python 复制代码
    class MyClass:
        __slots__ = ('name', 'age')

11. 内建函数和操作

  • 内建函数 :如 len(), range(), min(), max(), sum() 等。

    python 复制代码
    len([1, 2, 3])
  • 序列字面量 :创建列表、元组、集合。

    python 复制代码
    [1, 2, 3], (1, 2, 3), {1, 2, 3}
  • 字典字面量 :创建字典。

    python 复制代码
    {'key': 'value'}
  • 条件表达式 :简化 if-else 语句。

    python 复制代码
    'active' if is_active else 'inactive'
  • 迭代器解包 :在函数调用中解包迭代器。

    python 复制代码
    [a, b] = iter_range
  • 参数解包 :在函数调用中解包序列或字典。

    python 复制代码
    def func(a, b, c): pass
    func(*args, **kwargs)
  • 链式比较 :简化多重比较。

    python 复制代码
    a < b < c
  • 内建序列方法 :如 .append(), .extend(), .insert(), .remove(), .pop() 等。

    python 复制代码
    my_list.append('new item')
  • 内建字典方法 :如 .get(), .keys(), .values(), .items() 等。

    python 复制代码
    my_dict.get('key')
  • 内建集合操作 :如 .union(), .difference(), .intersection(), .symmetric_difference() 等。

    python 复制代码
    set_a.union(set_b)
  • 内建迭代器 :如 enumerate(), zip(), filter(), map() 等。

    python 复制代码
    enumerate(['a', 'b', 'c'])
  • 内建类型转换 :如 int(), float(), str(), bytes() 等。

    python 复制代码
    int('123')
  • 内建逻辑操作 :如 and, or, not

    python 复制代码
    x and y or z
  • 内建身份操作 :如 is, is not

    python 复制代码
    x is not None
  • 内建比较 :比较运算符 ==, !=, >, <, >=, <=

    python 复制代码
    x > y
  • 内建数学运算 :如 +, -, *, /, //, **

    python 复制代码
    x + y

12. 特殊方法

  • 特殊方法 :如 __init__(), __str__(), __repr__(), __len__() 等。

    python 复制代码
    class MyClass:
        def __init__(self, value):
            self.value = value

13. 元类和类创建

  • 使用 type 作为元类 :创建类的类。

    python 复制代码
    class MyClass(type):
        pass

14. 模块属性和包

  • 模块属性 :如 __all__ 定义可导入的模块成员。

    python 复制代码
    __all__ = ['func1', 'func2']
  • 命名空间包 :使用 __path__ 属性。

    python 复制代码
    __import__('pkgutil').extend_path(__path__, __name__)

15. 协程与异步IO

  • 异步上下文管理器 :使用 async with

    python 复制代码
    async def async_func():
        async with aiohttp.ClientSession() as session:
            pass

16. 格式化字符串字面量

  • f-strings :格式化字符串。

    python 复制代码
    name = 'Kimi'
    f"Hello, {name}!"

17. 文件操作

  • 文件上下文管理器 :使用 with open() 管理文件。

    python 复制代码
    with open('file.txt', 'r') as f:
        content = f.read()

18. 警告与反射

  • 警告机制 :使用 warnings 模块发出警告。

    python 复制代码
    import warnings
    warnings.warn("This is a warning message.")
  • 反射 :使用 getattr(), setattr(), delattr() 动态操作对象属性。

    python 复制代码
    getattr(obj, 'attr')

19. 垃圾回收与循环引用

  • 垃圾回收机制 :自动管理内存。

    python 复制代码
    # Python's garbage collector takes care of objects
  • 循环引用处理 :自动解除循环引用的 WeakRef

    python 复制代码
    import weakref
    weakref.ref(obj)

20. 内建数据类型操作

  • 序列操作 :如 +, *, in, not in

    python 复制代码
    [1, 2] + [3, 4]
  • 字典操作 :如 dict.pop(), dict.setdefault()

    python 复制代码
    my_dict.pop('key', 'default')
  • 集合操作 :如 set.add(), set.remove()

    python 复制代码
    my_set.add('new item')

21. 内建迭代与循环控制

  • 迭代器 :使用 iter() 创建迭代器。

    python 复制代码
    iter([1, 2, 3])
  • 循环控制 :使用 breakcontinue 控制循环流程。

    python 复制代码
    for element in iterable:
        if some_condition:
            break  # Exit the loop
        else:
            continue  # Skip to the next iteration

22. 内建比较与逻辑运算

  • 比较运算符==, !=, >, <, >=, <=

    python 复制代码
    x == y
  • 逻辑运算符and, or, not

    python 复制代码
    x and y or z

23. 内建身份与成员运算

  • 身份运算符is, is not

    python 复制代码
    x is y
  • 成员运算符in, not in

    python 复制代码
    'a' in ['a', 'b', 'c']
相关推荐
不写八个14 分钟前
Python办公自动化教程(005):Word添加段落
开发语言·python·word
_.Switch31 分钟前
Python机器学习框架介绍和入门案例:Scikit-learn、TensorFlow与Keras、PyTorch
python·机器学习·架构·tensorflow·keras·scikit-learn
赵荏苒43 分钟前
Python小白之Pandas1
开发语言·python
一眼万里*e1 小时前
fish-speech语音大模型本地部署
python·flask·大模型
结衣结衣.2 小时前
python中的函数介绍
java·c语言·开发语言·前端·笔记·python·学习
茫茫人海一粒沙2 小时前
Python 代码编写规范
开发语言·python
林浩2332 小时前
Python——异常处理机制
python
数据分析螺丝钉2 小时前
力扣第240题“搜索二维矩阵 II”
经验分享·python·算法·leetcode·面试
小蜗笔记3 小时前
在Python中实现多目标优化问题(7)模拟退火算法的调用
开发语言·python·模拟退火算法
TANGLONG2223 小时前
【C语言】数据在内存中的存储(万字解析)
java·c语言·c++·python·考研·面试·蓝桥杯