# 常用数据结构之列表(一) ## 为什么需要列表 假设要统计掷骰子6000次各点数出现次数,用6个变量分别计数会非常繁琐: ```python f1, f2, f3, f4, f5, f6 = 0, 0, 0, 0, 0, 0 # ...大量分支判断 ``` 用**列表**可以用一个变量保存多个数据,实现批量操作: ```python counters = [0] * 6 for _ in range(6000): face = random.randrange(1, 7) counters[face - 1] += 1 for face in range(1, 7): print(f'{face}点出现了{counters[face-1]}次') ``` ## 创建列表 ```python # 基本创建 items1 = [35, 12, 99, 68, 55] items2 = ['Python', 'Java', 'Go'] items3 = [100, 12.5, 'hello', True] # 可以混合类型,但不推荐 # 从其他序列转换 items4 = list(range(1, 10)) # [1, 2, 3, ..., 9] items5 = list('hello') # ['h', 'e', 'l', 'l', 'o'] ``` ## 列表运算 ```python a = [35, 12, 99, 45, 66] b = [45, 58, 29] # 拼接 print(a + b) # [35, 12, 99, 45, 66, 45, 58, 29] # 重复 print(b * 3) # [45, 58, 29, 45, 58, 29, 45, 58, 29] # 成员运算 print(29 in b) # True print(99 not in a) # False ``` ## 索引和切片 ```python items = ['apple', 'waxberry', 'pitaya', 'peach', 'watermelon'] # 正向索引:0 到 N-1 print(items[0]) # apple print(items[2]) # pitaya # 反向索引:-1 到 -N print(items[-1]) # watermelon print(items[-4]) # waxberry # 修改元素 items[2] = 'durian' # 切片 [start:end:step] print(items[1:3]) # ['waxberry', 'durian'] print(items[::2]) # ['apple', 'durian', 'watermelon'] print(items[::-1]) # 翻转列表 ``` > **注意**:索引越界会引发 `IndexError: list index out of range`。 ## 遍历列表 ```python languages = ['Python', 'Java', 'C++', 'Kotlin'] # 方式1:索引遍历 for i in range(len(languages)): print(languages[i]) # 方式2:直接遍历元素(推荐) for lang in languages: print(lang) ``` ## 总结 - 列表用 `[]` 创建,可存储多个任意类型的元素 - 支持索引、切片、拼接、重复、成员运算 - 使用 `for elem in list` 直接遍历元素