Python 进阶特性集锦--列表推导式、装饰器、列表和字典解包

Python中有很多常用的模块和语法糖,以下是其中的一些,以及配套的示例代码,旨在抛砖引玉,启发更多场景运用。

1. 列表推导式 (List Comprehensions)

列表推导式是一种优雅的构建列表的方法,它可以用来替代传统的循环语句。

示例:

# 传统循环构建列表
squares = []
for x in range(10):
    squares.append(x * x)

# 列表推导式
squares = [x * x for x in range(10)]

2. 字典推导式 (Dictionary Comprehensions)

与列表推导式类似,字典推导式可以用来通过迭代生成字典。

示例:

# 创建一个字典,键为数字,值为该数字的平方
squares_dict = {x: x * x for x in range(5)}

3. 生成器表达式 (Generator Expressions)

生成器表达式与列表推导式类似,但它产生的是一个迭代器而不是列表,可以节省内存。

示例:

# 生成器表达式
squares_gen = (x * x for x in range(10))

# 使用生成器
for square in squares_gen:
    print(square)

4. 函数默认参数 (Default Argument Values)

函数可以有默认参数值,这意味着调用函数时可以不传递这些参数,而是使用默认值。

示例:

def greet(name, msg="Hello"):
    print(f"{msg}, {name}")

greet("John")  # 输出: Hello, John
greet("John", "Good morning")  # 输出: Good morning, John

5. *args 和 **kwargs

在函数定义中使用 *args**kwargs 可以让你处理不确定数量的位置参数和关键字参数。

示例:

def func(*args, **kwargs):
    print("args:", args)
    print("kwargs:", kwargs)

func(1, 2, 3, a=4, b=5)

6. 装饰器 (Decorators)

装饰器是修改函数或类的行为的一种方式。

示例:

def my_decorator(func):
    def wrapper():
        print("Something is happening before the function is called.")
        func()
        print("Something is happening after the function is called.")
    return wrapper

@my_decorator
def say_hello():
    print("Hello!")

say_hello()

7. f-strings (Formatted String Literals)

f-strings 是 Python 3.6 引入的,提供了一种嵌入表达式到字符串常量中的方式。

示例:

name = "John"
age = 30
print(f"Hello, My name is {name} and I am {age} years old.")

8. 高级字符串格式化 (字符串的 format 方法)

字符串的format方法提供了一种格式化字符串的高级方法。

示例:

# 使用format方法格式化字符串
text = "The temperature today is {temp} degrees outside, which feels like {feeling}.".format(temp=18, feeling="chilly")
print(text)

9. 列表和字典解包 (List and Dictionary Unpacking)

解包操作可以用于函数调用中,允许你将列表或字典的内容作为独立的参数传递。

示例:

# 列表解包
numbers = [1, 2, 3]
print(*numbers)  # 1 2 3

# 字典解包
info = {'name': 'Alice', 'age': 25}
def greet(name, age):
    print(f"Hello {name}, you are {age} years old.")

greet(**info)  # Hello Alice, you are 25 years old.

10. 参数化装饰器 (Parametrized Decorators)

装饰器可以带参数,以此来提供更多的灵活性。

示例:

def repeat(times):
    def decorator_repeat(func):
        @functools.wraps(func)
        def wrapper_repeat(*args, **kwargs):
            for _ in range(times):
                value = func(*args, **kwargs)
            return value
        return wrapper_repeat
    return decorator_repeat

@repeat(times=4)
def function_to_repeat():
    print("Repeating")

function_to_repeat()

11. 文件操作 (File Operations)

Python的内置函数 open() 可以用于文件的读取和写入。

示例:

# 写入文件
with open('example.txt', 'w') as file:
    file.write("Hello, World!")

# 读取文件
with open('example.txt', 'r') as file:
    content = file.read()
    print(content)

12. 类 (Classes)

Python 是一种面向对象的语言,支持通过类定义复杂的数据结构。

示例:

class Dog:
    def __init__(self, name):
        self.name = name

    def speak(self):
        return f"{self.name} says Woof!"

# 创建类的实例
my_dog = Dog("Buddy")
print(my_dog.speak())

13. 迭代器和生成器 (Iterators and Generators)

迭代器允许你遍历一个集合,而生成器允许你按需生成值,而不是一次性地计算出所有值。

示例 - 迭代器:

# 迭代器示例
iterable = iter([1, 2, 3])
print(next(iterable))  # 输出 1
print(next(iterable))  # 输出 2

示例 - 生成器:

def countdown(number):
    while number > 0:
        yield number
        number -= 1

# 使用生成器
for count in countdown(5):
    print(count)

14. 匹配语句 (Pattern Matching)

Python 3.10 引入了结构化模式匹配,类似于其他语言中的 switchmatch 语句。

示例:

from dataclasses import dataclass

@dataclass
class Point:
    x: int
    y: int

def location(point: Point):
    match point:
        case Point(x=0, y=0):
            print("Origin")
        case Point(x=0, y=y):
            print(f"Y={y}")
        case Point(x=x, y=0):
            print(f"X={x}")
        case Point():
            print("Somewhere else")

location(Point(0, 0))  # Origin

15. enumerate 函数

enumerate 函数用于在遍历循环中同时获取元素和其索引。

示例:

names = ['Alice', 'Bob', 'Charlie']
for index, name in enumerate(names):
    print(f"Index {index}: {name}")

16. 数据类型转换 (Type Conversion)

Python 允许你在不同数据类型之间进行转换。

示例:

# 整数转换为浮点数
num_int = 5
num_float = float(num_int)
print(num_float)  # 输出 5.0

# 字符串转换为列表
string = "hello"
string_list = list(string)
print(string_list)  # 输出 ['h', 'e', 'l', 'l', 'o']

17. lambda 函数 (Lambda Functions)

lambda 函数是一种简洁的定义函数的方法,通常用于需要函数对象的地方,但又不想使用完整的 def 语句。

示例:

# lambda 函数
add = lambda x, y: x + y
print(add(2, 3))  # 输出 5

18. 列表和字典的方法 (List and Dictionary Methods)

Python 的内置数据结构如列表和字典有许多有用的方法。

示例:

# 列表方法
my_list = [1, 2, 3]
my_list.append(4)
print(my_list)  # 输出 [1, 2, 3, 4]

# 字典方法
my_dict = {'a': 1, 'b': 2}
print(my_dict.keys())  # 输出 dict_keys(['a', 'b'])

19. 装饰器 (Decorators)

装饰器允许你修改函数的行为,而不改变其结构。

示例:

# 装饰器
def my_decorator(func):
    def wrapper():
        print("Something is happening before the function is called.")
        func()
        print("Something is happening after the function is called.")
    return wrapper

@my_decorator
def say_hello():
    print("Hello!")

say_hello()

20. 环境变量 (Environment Variables)

Python 可以读取和修改操作系统的环境变量,这对于配置程序行为很有用。

示例:

import os

# 设置环境变量
os.environ['MY_VAR'] = 'some_value'

# 获取环境变量
print(os.environ.get('MY_VAR'))  # 输出 'some_value'

21. 迭代工具 (Iteration Tools)

itertools 模块提供了许多用于迭代的工具,能够创建高效的循环。

示例:

from itertools import cycle

# cycle 会无限循环迭代对象
count = 0
for item in cycle(['red', 'blue', 'green']):
    if count > 7:
        break
    print(item)
    count += 1

22. 上下文管理器 (Context Managers)

上下文管理器用于资源的自动分配和释放,通常与with语句一起使用。

示例:

from contextlib import contextmanager

@contextmanager
def managed_file(name):
    try:
        f = open(name, 'w')
        yield f
    finally:
        f.close()

with managed_file('hello.txt') as f:
    f.write('hello, world!')

23. 多线程 (Threading)

Python 中的多线程可以用来执行并行任务。

示例:

import threading

def print_numbers():
    for i in range(5):
        print(i)

thread = threading.Thread(target=print_numbers)
thread.start()
thread.join()

24. 多进程 (Multiprocessing)

Python 中的多进程用于在独立的内存空间内并行执行任务。

示例:

from multiprocessing import Process

def print_numbers():
    for i in range(5):
        print(i)

if __name__ == '__main__':
    process = Process(target=print_numbers)
    process.start()
    process.join()

25. 正则表达式 (Regular Expressions)

re模块提供了一套丰富的正则表达式工具,用于字符串匹配和处理。

示例:

import re

pattern = re.compile(r'\d+')
result = pattern.findall('hello 1234 world 5678')
print(result)  # ['1234', '5678']

26. 构造型注解 (Structural Subtyping)

Python 3.8 引入了 Protocol 类,允许基于结构子类型化(又称为鸭子类型)进行类型检查。

示例:

from typing import Protocol

class Greeter(Protocol):
    name: str
    def greet(self) -> str:
        ...

def say_hello(item: Greeter):
    print(item.greet())

class Person:
    name: str
    def greet(self) -> str:
        return f"Hello, my name is {self.name}"

person = Person()
person.name = "Alice"
say_hello(person)

27. 异步编程 (Asynchronous Programming)

asyncio模块提供了编写单线程并发代码的设施。

示例:

import asyncio

async def hello():
    await asyncio.sleep(1)
    print('Hello, World!')

asyncio.run(hello())

28. 数据类 (Data Classes)

在Python 3.7+中,dataclasses模块用于快速创建包含数据的类。

示例:

from dataclasses import dataclass

@dataclass
class Product:
    name: str
    price: float

product = Product(name="Widget", price=19.99)
print(product.name)  # Widget

29. 类型注解 (Type Annotations)

Python 3.5+允许开发者在代码中添加类型注解,提高代码的清晰度和可维护性。

示例:

def add(a: int, b: int) -> int:
    return a + b

result = add(1, 2)
print(result)  # 3

30. 枚举 (Enumerations)

使用enum模块创建枚举,它是一种使代码更具可读性的方法。

示例:

from enum import Enum, auto

class Color(Enum):
    RED = auto()
    GREEN = auto()
    BLUE = auto()

print(Color.RED)  # Color.RED

31. 集合 (Sets)

集合是一个无序且不包含重复元素的集。它们常用于测试成员资格、去重和其它数学运算。

示例:

# 创建集合
my_set = {1, 2, 3, 4, 5}
print(my_set)  # {1, 2, 3, 4, 5}

# 添加元素
my_set.add(6)
print(my_set)  # {1, 2, 3, 4, 5, 6}

# 交集、并集、差集操作
another_set = {4, 5, 6, 7, 8}
print(my_set.intersection(another_set))  # {4, 5, 6}
print(my_set.union(another_set))         # {1, 2, 3, 4, 5, 6, 7, 8}
print(my_set.difference(another_set))    # {1, 2, 3}

32. 集合推导式 (Set Comprehensions)

类似于列表推导式,集合推导式提供了一种简洁的方式来创建集合。

示例:

# 使用集合推导式创建集合
squared_set = {x ** 2 for x in range(10)}
print(squared_set)  # {0, 1, 4, 9, 16, 25, 36, 49, 64, 81}

33. 切片 (Slicing)

切片操作可以让你取得序列的一部分。

示例:

# 切片操作
my_list = [0, 1, 2, 3, 4, 5]
print(my_list[2:5])  # [2, 3, 4]
print(my_list[:3])   # [0, 1, 2]
print(my_list[3:])   # [3, 4, 5]
print(my_list[-2:])  # [4, 5]

34. 链式比较 (Chained Comparisons)

链式比较可以让你更简洁地进行多个比较操作。

示例:

# 链式比较
a = 5
print(1 < a < 10)  # True
print(10 < a < 20)  # False

35. 任意精度整数 (Arbitrary Precision Integers)

Python的整数类型没有固定的大小限制,可以处理任意大小的整数。

示例:

# 大整数运算
big_number = 123456789123456789123456789123456789123456789123456789
print(big_number + 1)  
# 123456789123456789123456789123456789123456789123456789123457790

36. with 语句 (Context Managers)

with 语句用于包裹代码块的执行,以确保即使出现异常,资源也能被正确管理。

示例:

# 文件操作
with open('file_path', 'w') as file:
    file.write('Hello, World!')

37. 内存视图 (Memory Views)

memoryview 对象可以让你在不复制内容的情况下操作同一块内存中的不同部分。

示例:

# 内存视图
data = bytearray('abc', 'utf-8')
view = memoryview(data)
print(view[0])  # 97 (ASCII码值)

view[1] = ord('d')
print(data)  # bytearray(b'adc')

38. Walrus Operator (:=)

Python 3.8 引入了沃尔拉斯操作符,或称为赋值表达式,允许在表达式内部进行赋值。

示例:

# 使用Walrus Operator在表达式中进行赋值
if (n := len([1, 2, 3])) > 2:
    print(f"List is too long ({n} elements, expected <= 2)")

39. 路径操作 (pathlib)

pathlib 模块提供了一个面向对象的文件系统路径操作方式。

示例:

from pathlib import Path

# 创建Path对象
p = Path('/etc')

# 列出目录内容
for child in p.iterdir():
    if child.is_file():
        print(child)

40. Counter 使用

collections 模块中的 Counter 类是一个简单的计数器工具,用于计算可哈希对象的数量。

示例:

from collections import Counter

# 计算元素出现的次数
c = Counter('hello world')
print(c)  # Counter({'l': 3, 'o': 2, 'h': 1, 'e': 1, ' ': 1, 'w': 1, 'r': 1, 'd': 1})

41. defaultdict 使用

collections 模块中的 defaultdict 类自动为字典提供默认值。

示例:

from collections import defaultdict

# 使用defaultdict来处理不存在的键
dd = defaultdict(int)
dd['key'] += 1
print(dd['key'])  # 输出 1

42. 进程间通信 (multiprocessing)

multiprocessing 模块支持进程间通信。

示例:

from multiprocessing import Process, Queue

def worker(q):
    q.put('Hello from the other side')

if __name__ == '__main__':
    q = Queue()
    p = Process(target=worker, args=(q,))
    p.start()
    print(q.get())  # 输出 'Hello from the other side'
    p.join()

43. 类型提示 (Type Hints)

Python 3.5 引入了类型提示,用于静态类型检查。

示例:

from typing import List

def greet_all(names: List[str]):
    for name in names:
        print(f"Hello, {name}")

greet_all(["Alice", "Bob", "Charlie"])

44. functools.lru_cache 缓存

functools.lru_cache 提供了一个简单的缓存机制。

示例:

from functools import lru_cache

@lru_cache(maxsize=None)
def fib(n):
    if n < 2:
        return n
    return fib(n-1) + fib(n-2)

print(fib(100))

45. itertools 组合工具

itertools 模块提供了一系列用于创建迭代器的组合工具。

示例:

from itertools import permutations

# 输出字符串的所有排列
for p in permutations('abc'):
    print(''.join(p))

46. functools.partial 偏函数

functools.partial 用于创建一个新的偏函数,可以“冻结”一些函数参数。

示例:

from functools import partial

def multiply(x, y):
    return x * y

# 创建一个新函数,第一个参数固定为2
dbl = partial(multiply, 2)
print(dbl(4))  # 输出 8

47. asyncawait

Python 3.5 引入的关键字,用于编写协程,以便执行异步IO操作。

示例:

import asyncio

async def main():
    print('Hello')
    await asyncio.sleep(1)
    print('World')

asyncio.run(main())

48. 联合类型 (Union Types)

Python 3.10 引入的 | 操作符,用于表示变量可以是多种类型之一。

示例:

from typing import Union

def greet(name: Union[str, list]):
    if isinstance(name, str):
        print(f"Hello, {name}")
    else:
        for n in name:
            print(f"Hello, {n}")

greet("Alice")
greet(["Bob", "Charlie"])

49. 字典合并 (Dictionary Merging)

Python 3.9 引入了合并和更新字典的操作符 ||=

示例:

x = {"key1": "value1"}
y = {"key2": "value2"}

z = x | y  # 合并字典
print(z)  # {'key1': 'value1', 'key2': 'value2'}
  • 18
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值