alist[x:y]#表示区间[x,y),注意区间是左开右闭 alist[x:y:w]#表示区间[x,y),同时步进为w alist[:y]#左端省略不写时表示序列的起始位置 alist[x:]#右端省略不写时表示序列的终止位置
alist[-1]#取最后一个元素 alist[-2:]#取最后两个元素 alist[-2:-1]#和普通切片一样,这里的区间是左开右闭的,取的是倒数第二个元素
'ABCDEF'[4:]#字符串也可以切片
>>> s = slice(None,5) >>> "hello world"[s] 'hello'
# 本代码由 AI 生成 # 定义一个lambda表达式计算两个数的和 add = lambda x, y: x + y # 使用lambda表达式 result = add(10, 20) print("The sum is:", result) # 输出: The sum is: 30 # 用于列表排序的lambda表达式 students = [ {"name": "Alice", "score": 88}, {"name": "Bob", "score": 72}, {"name": "Charlie", "score": 95} ] # 根据分数排序 sorted_students = sorted(students, key=lambda student: student["score"]) print("Sorted students by score:", sorted_students) # 输出: Sorted students by score: [{'name': 'Bob', 'score': 72}, {'name': 'Alice', 'score': 88}, {'name': 'Charlie', 'score': 95}]
修饰器是一个函数。其(至少)接受一个函数作为参数,返回一个新的函数,新的函数被加上了某种「功能」
使用修饰器的(快捷)语法是:在函数前面使用@xxx
推荐资料:Python Cookbook 3rd