• Python语法糖大全


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

    1. 集合与序列操作

    • 列表推导式:创建列表。
      [x**2 for x in range(10)]
      
      • 1
    • 字典推导式:创建字典。
      {x: x**2 for x in range(10)}
      
      • 1
    • 集合推导式:创建集合。
      {x**2 for x in range(10)}
      
      • 1
    • 条件列表推导:在列表推导中使用条件表达式。
      [x for x in range(10) if x % 2 == 0]
      
      • 1
    • 条件字典推导:在字典推导中使用条件表达式。
      {x: x**2 for x in range(10) if x % 2 != 0}
      
      • 1
    • 生成器表达式:创建迭代器。
      (x**2 for x in range(10))
      
      • 1
    • 字符串字面量:单引号或双引号表示的字符串。
      s = "This is a string in double quotes."
      
      • 1
    • 原始字符串:使用 r 前缀表示,忽略转义字符。
      raw_str = r"New line is represented as \n"
      
      • 1
    • 多行字符串:使用三个引号表示。
      multi_line_str = """This is a multi-line
                         string with two lines."""
      
      • 1
      • 2

    2. 赋值与解包

    • 多重赋值:一次性赋值多个变量。
      a, b = 1, 2
      
      • 1
    • 扩展的可迭代解包:函数调用中解包可迭代对象。
      *a, b = [1, 2, 3, 4]
      
      • 1
    • 解包赋值:从序列中解包值赋给多个变量。
      a, *b, c = [0, 1, 2, 3, 4]
      
      • 1

    3. 函数与Lambda

    • 装饰器:修改函数或方法的行为。
      @my_decorator
      def say_hello():
          print("Hello!")
      
      • 1
      • 2
      • 3
    • lambda 函数:创建匿名函数。
      add = lambda x, y: x + y
      
      • 1
    • 关键字参数:使用 **kwargs 接受任意数量的关键字参数。
      def print_kwargs(**kwargs):
          for key, value in kwargs.items():
              print(f"{key}: {value}")
      
      • 1
      • 2
      • 3

    4. 控制流

    • 条件表达式:一行 if-else 逻辑。
      max_value = a if a > b else b
      
      • 1
    • 异常处理:使用 try…except 语句处理错误。
      try:
          x = int(input("Please enter a number: "))
      except ValueError:
          print("That's not a valid number!")
      
      • 1
      • 2
      • 3
      • 4
    • 断言:调试目的的检查。
      assert x == y, "x does not equal y"
      
      • 1

    5. 上下文管理

    • with 语句:资源管理。
      with open('file.txt') as f:
          content = f.read()
      
      • 1
      • 2

    6. 类和对象

    • 属性装饰器:创建管理对象属性的方法。
      class MyClass:
          @property
          def value(self):
              return self._value
          @value.setter
          def value(self, new_value):
              self._value = new_value
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
    • 命名元组:创建带有命名字段的元组子类。
      from collections import namedtuple
      Point = namedtuple('Point', ['x', 'y'])
      
      • 1
      • 2

    7. 模块和包

    • 相对与绝对导入:模块的相对或绝对导入。
      from . import my_module  # 相对导入
      from mypackage import my_module  # 绝对导入
      
      • 1
      • 2

    8. 类型提示

    • 类型注解:指定变量的预期类型。
      def get_addition_result(a: int, b: int) -> int:
          return a + b
      
      • 1
      • 2

    9. 异步编程

    • 异步函数:使用 asyncawait 编写异步代码。
    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())
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    10. 其他

    • 表达式末尾的逗号:在表达式末尾使用逗号,方便添加或删除元素。
      my_list = [1, 2, 3, ]
      
      • 1
    • 星号参数和双星号参数:在函数定义中收集任意数量的参数。
      def func(*args, **kwargs):
          print(args, kwargs)
      
      • 1
      • 2
    • 异常的 as 用法:捕获异常的实例。
      try:
          1 / 0
      except ZeroDivisionError as e:
          print(f"Caught an exception: {e}")
      
      • 1
      • 2
      • 3
      • 4
    • 海象运算符:在表达式中进行赋值(Python 3.8+)。
      # Python 3.8+
      (element) = [1, 2, 3]
      
      • 1
      • 2
    • 使用 __slots__:限制实例属性,优化内存使用。
      class MyClass:
          __slots__ = ('name', 'age')
      
      • 1
      • 2

    11. 内建函数和操作

    • 内建函数:如 len(), range(), min(), max(), sum() 等。
      len([1, 2, 3])
      
      • 1
    • 序列字面量:创建列表、元组、集合。
      [1, 2, 3], (1, 2, 3), {1, 2, 3}
      
      • 1
    • 字典字面量:创建字典。
      {'key': 'value'}
      
      • 1
    • 条件表达式:简化 if-else 语句。
      'active' if is_active else 'inactive'
      
      • 1
    • 迭代器解包:在函数调用中解包迭代器。
      [a, b] = iter_range
      
      • 1
    • 参数解包:在函数调用中解包序列或字典。
      def func(a, b, c): pass
      func(*args, **kwargs)
      
      • 1
      • 2
    • 链式比较:简化多重比较。
      a < b < c
      
      • 1
    • 内建序列方法:如 .append(), .extend(), .insert(), .remove(), .pop() 等。
      my_list.append('new item')
      
      • 1
    • 内建字典方法:如 .get(), .keys(), .values(), .items() 等。
      my_dict.get('key')
      
      • 1
    • 内建集合操作:如 .union(), .difference(), .intersection(), .symmetric_difference() 等。
      set_a.union(set_b)
      
      • 1
    • 内建迭代器:如 enumerate(), zip(), filter(), map() 等。
      enumerate(['a', 'b', 'c'])
      
      • 1
    • 内建类型转换:如 int(), float(), str(), bytes() 等。
      int('123')
      
      • 1
    • 内建逻辑操作:如 and, or, not
      x and y or z
      
      • 1
    • 内建身份操作:如 is, is not
      x is not None
      
      • 1
    • 内建比较:比较运算符 ==, !=, >, <, >=, <=
      x > y
      
      • 1
    • 内建数学运算:如 +, -, *, /, //, **
      x + y
      
      • 1

    12. 特殊方法

    • 特殊方法:如 __init__(), __str__(), __repr__(), __len__() 等。
      class MyClass:
          def __init__(self, value):
              self.value = value
      
      • 1
      • 2
      • 3

    13. 元类和类创建

    • 使用 type 作为元类:创建类的类。
      class MyClass(type):
          pass
      
      • 1
      • 2

    14. 模块属性和包

    • 模块属性:如 __all__ 定义可导入的模块成员。
      __all__ = ['func1', 'func2']
      
      • 1
    • 命名空间包:使用 __path__ 属性。
      __import__('pkgutil').extend_path(__path__, __name__)
      
      • 1

    15. 协程与异步IO

    • 异步上下文管理器:使用 async with
      async def async_func():
          async with aiohttp.ClientSession() as session:
              pass
      
      • 1
      • 2
      • 3

    16. 格式化字符串字面量

    • f-strings:格式化字符串。
      name = 'Kimi'
      f"Hello, {name}!"
      
      • 1
      • 2

    17. 文件操作

    • 文件上下文管理器:使用 with open() 管理文件。
      with open('file.txt', 'r') as f:
          content = f.read()
      
      • 1
      • 2

    18. 警告与反射

    • 警告机制:使用 warnings 模块发出警告。
      import warnings
      warnings.warn("This is a warning message.")
      
      • 1
      • 2
    • 反射:使用 getattr(), setattr(), delattr() 动态操作对象属性。
      getattr(obj, 'attr')
      
      • 1

    19. 垃圾回收与循环引用

    • 垃圾回收机制:自动管理内存。
      # Python's garbage collector takes care of objects
      
      • 1
    • 循环引用处理:自动解除循环引用的 WeakRef
      import weakref
      weakref.ref(obj)
      
      • 1
      • 2

    20. 内建数据类型操作

    • 序列操作:如 +, *, in, not in
      [1, 2] + [3, 4]
      
      • 1
    • 字典操作:如 dict.pop(), dict.setdefault()
      my_dict.pop('key', 'default')
      
      • 1
    • 集合操作:如 set.add(), set.remove()
      my_set.add('new item')
      
      • 1

    21. 内建迭代与循环控制

    • 迭代器:使用 iter() 创建迭代器。
      iter([1, 2, 3])
      
      • 1
    • 循环控制:使用 breakcontinue 控制循环流程。
      for element in iterable:
          if some_condition:
              break  # Exit the loop
          else:
              continue  # Skip to the next iteration
      
      • 1
      • 2
      • 3
      • 4
      • 5

    22. 内建比较与逻辑运算

    • 比较运算符==, !=, >, <, >=, <=
      x == y
      
      • 1
    • 逻辑运算符and, or, not
      x and y or z
      
      • 1

    23. 内建身份与成员运算

    • 身份运算符is, is not
      x is y
      
      • 1
    • 成员运算符in, not in
      'a' in ['a', 'b', 'c']
      
      • 1
  • 相关阅读:
    【电商】跨境电商「保税」业务(附支付宝、微信对接指南)
    Java子类继承父类私有方法属性问题讲解
    Connect-The-Dots_2
    [.NET开发者的福音]一个方便易用的在线.NET代码编辑工具.NET Fiddle
    广州移动中兴B860AV3.1-M2_S905L3安卓9.0线刷包
    股票python量化交易020-双均线策略(上)
    java计算机毕业设计课程与成绩管理MyBatis+系统+LW文档+源码+调试部署
    买美容仪看这篇,全网超火美容仪真实测评
    Map集合的遍历:键值对
    【webrtc】VCMSessionInfo 合并一个可解码的帧
  • 原文地址:https://blog.csdn.net/oYeZhou/article/details/138145504