s[::-1]
是 Python 的 切片语法 ,它只能用在 支持序列(sequence)类型 的对象上,也就是有顺序、可以通过整数索引访问的对象。
典型可以用的类型:
-
字符串
str
✅s = "hello"
print(s[::-1]) # 输出 "olleh" -
列表
list
✅lst = [1, 2, 3, 4, 5]
print(lst[::-1]) # 输出 [5, 4, 3, 2, 1] -
元组
tuple
✅t = (1, 2, 3)
print(t[::-1]) # 输出 (3, 2, 1)
不能直接用的类型:
-
字典
dict
❌d = {1: "a", 2: "b"}
print(d[::-1]) # 会报错 TypeError: 'dict' object is not subscriptable
字典是 映射类型,没有顺序索引,所以不支持切片。