1. List(列表)
列表是一个有序的、可变的序列,可以存储不同类型的元素。
1.1 创建
1 2 3 4 5 6 7
| a = [] b = list()
nums = [1, 2, 3, 4] mixed = [1, "hello", True, 3.14]
|
1.2 常用操作
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| nums = [10, 20, 30]
print(nums[0]) print(nums[-1])
nums[1] = 25
nums.append(40) nums.insert(1, 15)
nums.remove(25) del nums[0] x = nums.pop()
print(30 in nums) print(nums.index(30))
print(len(nums))
nums.sort() nums.reverse()
|
1.3 遍历
1 2 3 4 5
| for x in nums: print(x)
for i, x in enumerate(nums): print(i, x)
|
2. Dict(字典)
字典是 键值对(key-value) 组成的集合,键唯一,值可重复。常用于表示映射关系。
2.1 创建
1 2 3 4 5 6
| d = {} d2 = dict()
person = {"name": "Alice", "age": 25, "city": "Beijing"}
|
2.2 常用操作
1 2 3 4 5 6 7 8 9 10 11 12 13
| print(person["name"]) print(person.get("age")) print(person.get("gender", "unknown"))
person["age"] = 26 person["gender"] = "female"
del person["city"] person.pop("age") person.clear()
|
2.3 遍历
1 2 3 4 5 6 7 8 9 10
| person = {"name": "Alice", "age": 25, "city": "Beijing"}
for key in person: print(key, person[key])
for key, value in person.items(): print(key, value)
for value in person.values(): print(value)
|
2.4 其他方法
1 2 3
| keys = person.keys() values = person.values() items = person.items()
|
3. List vs Dict 对比
特性 |
List(列表) |
Dict(字典) |
存储方式 |
有序序列 |
键值对集合 |
索引方式 |
下标(数字) |
键(可哈希) |
是否允许重复元素 |
允许 |
键不能重复 |
使用场景 |
顺序数据、栈、队列 |
映射关系、查表 |