本文共 3125 字,大约阅读时间需要 10 分钟。
Python 提供了强大的切片功能,类似于Excel 中数据透视表的切片器。通过指定索引范围,可以轻松提取列表中所需的部分数据。
L = ['Michael', 'Sarah', 'Tracy', 'Bob', 'Jack']L[0:3] # 提取前三个元素:['Michael', 'Sarah', 'Tracy']S = list(range(100))S[0:100:9] # 提取索引为 9 的倍数的元素:[0, 9, 18, ..., 99]
切片操作不仅适用于列表,还可以用于 tuple:
tuple_list = [1, 2, 3]tuple_result = tuple_list[1:3] # tuple(2, 3)
Python 的迭代机制允许对各种可迭代对象(如 list、tuple、dict、str 等)进行统一处理。可通过 for 循环遍历这些对象。
for item in [1, 2, 3]: print(item)
enumerate 函数可将索引和元素同时遍历:
for index, value in enumerate(['a', 'b', 'c']): print(f'Index: {index}, Value: {value}') 检查对象是否可迭代:
from collections import Iterableisinstance('abc', Iterable) # Trueisinstance([1, 2, 3], Iterable) # Trueisinstance(123, Iterable) # False 列表生成式(List Comprehensions)是一种强大的工具,用于创建高效的 list。语法简洁,效率高。
tiangan = '甲乙丙丁戊己庚辛壬癸'dizhi = '子丑寅卯辰巳午未申酉戌亥'jiazi = [tiangan[x % len(tiangan)] + dizhi[x % len(dizhi)] for x in range(60)]
支持条件判断和多层循环:
[x * x for x in range(1, 11) if x % 2 == 0] # [4, 16, 36, 64, 100][m + n for m in 'ABC' for n in 'XYZ'] # ['AX', 'AY', 'AZ', 'BX', 'BY', 'BZ', 'CX', 'CY', 'CZ']
生成器是一种高效的数据结构,适合处理大数据量的迭代操作。生成器在循环时按需计算,避免了存储所有数据的开销。
L = [x * x for x in range(10)]g = (x * x for x in range(10)) # 生成器对象try: print(next(g)) # 0 print(next(g)) # 1except StopIteration: print('结束') for 循环遍历。iter() 函数将可迭代对象转换为迭代器,支持通过 next() 获取下一个元素。Python 支持函数式编程,通过高阶函数实现函数的组合与传递。
变量可以指向函数:
abs(-10) # 10f = absf(-10) # 10
函数名也是变量:
abs = 10print(abs(-10)) # 错误:int object is not callable
传入函数:
def f(x): return x + 1g = fprint(g(5)) # 6
map:将函数作用于序列的每个元素:
def f(x): return x * xr = map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9])list(r) # [1, 4, 9, 16, 25, 36, 49, 64, 81]
reduce:对序列进行递归化简:
from functools import reducedef f(a, b): return a + br = reduce(f, [1, 2, 3, 4])print(r) # 10
filter:过滤序列:
def is_odd(n): return n % 2 == 1filtered = list(filter(is_odd, [1, 2, 4, 5, 6, 9, 10, 15]))print(filtered) # [1, 5, 9, 15]
sorted:对 list 进行排序:
sorted_list = sorted([36, 5, -12, 9, -21])print(sorted_list) # [-21, -12, 5, 9, 36]
闭包(Closure):
def lazy_sum(*args): def sum(): total = 0 for n in args: total += n return total return sumsum_func = lazy_sum(1, 2, 3)print(sum_func()) # 6
匿名函数(Lambda):
list(map(lambda x: x * x, [1, 2, 3, 4, 5, 6, 7, 8, 9])) # [1, 4, 9, 16, 25, 36, 49, 64, 81]
装饰器:
import functoolsdef log(func): @functools.wraps(func) def wrapper(*args, **kw): print(f'call {func.__name__():}') return func(*args, **kw) return wrapper@logdef now(): print('2015-3-25')now() # 输出: call now()模块:一个 .py 文件称为模块。
包:通过目录组织模块,避免命名冲突。每个包必须包含 __init__.py 文件。
使用模块:
import sysdef test(): args = sys.argv if len(args) == 1: print('Hello, world!') elif len(args) == 2: print(f'Hello, {args[1]}!') else: print('Too many arguments!')if __name__ == '__main__': test()_xxx)不应被直接引用。pip install Pillow # 安装第三方库
通过以上内容,可以看到 Python 的高级特性非常强大,适用于不同的编程场景。
转载地址:http://markz.baihongyu.com/