python列表、元组、字典、集合
python列表、元组、字典、集合详解一、列表
列表是有序的可变集合。
创建列表:使用方括号 []。
访问元素:通过索引访问。
修改元素:通过索引修改。
常用方法:append(), extend(), insert(), remove(), pop(), sort(), reverse() 等。
fruits = ["apple", "banana", "cherry"]
# 访问元素
print(fruits[0]) # 输出: apple
# 修改元素
fruits[0] = "orange"
print(fruits) # 输出: ['orange', 'banana', 'cherry']
# 添加元素
fruits.append("grape")
print(fruits) # 输出: ['orange', 'banana', 'cherry', 'grape']
# 插入元素
fruits.insert(1, "kiwi")
print(fruits) # 输出: ['orange', 'kiwi', 'banana', 'cherry', 'grape']
# 删除元素
fruits.remove("banana")
print(fruits) # 输出: ['orange', 'kiwi', 'cherry', 'grape']
# 排序
fruits.sort()
print(fruits) # 输出: ['cherry', 'grape', 'kiwi', 'orange']二、元组
元组是有序的不可变集合。
创建元组:使用圆括号 ()。
访问元素:通过索引访问。
元组是不可变的:不能修改、添加或删除元素。
coordinates = (10, 20) # 访问元素 print(coordinates[0]) # 输出: 10 # 元组解包 x, y = coordinates print(x, y) # 输出: 10 20
三、字典
字典是键值对的无序集合。
创建字典:使用花括号 {}。
访问元素:通过键访问。
修改元素:通过键修改。
常用方法:keys(), values(), items(), get(), update(), pop(), clear() 等。
person = {"name": "Alice","age": 25,"city": "New York"}
# 访问元素
print(person["name"]) # 输出: Alice
# 修改元素
person["age"] = 26
print(person) # 输出: {'name': 'Alice', 'age': 26, 'city': 'New York'}
# 添加元素
person["email"] = "alice@example.com"
print(person) # 输出: {'name': 'Alice', 'age': 26, 'city': 'New York', 'email': 'alice@example.com'}
# 删除元素
del person["city"]
print(person) # 输出: {'name': 'Alice', 'age': 26, 'email': 'alice@example.com'}
# 获取所有键
print(person.keys()) # 输出: dict_keys(['name', 'age', 'email'])
# 获取所有值
print(person.values()) # 输出: dict_values(['Alice', 26, 'alice@example.com'])
# 获取所有键值对
print(person.items()) # 输出: dict_items([('name', 'Alice'), ('age', 26), ('email', 'alice@example.com')])四、集合
集合是无序的不重复元素集合。
创建集合:使用花括号 {} 或 set() 函数。
添加元素:使用 add() 方法。
删除元素:使用 remove() 或 discard() 方法。
常用方法:union(), intersection(), difference(), issubset(), issuperset() 等。
fruits = {"apple", "banana", "cherry"}
# 添加元素
fruits.add("orange")
print(fruits) # 输出: {'banana', 'cherry', 'apple', 'orange'}
# 删除元素
fruits.remove("banana")
print(fruits) # 输出: {'cherry', 'apple', 'orange'}
# 集合运算
set1 = {1, 2, 3}
set2 = {3, 4, 5}
# 并集
print(set1.union(set2)) # 输出: {1, 2, 3, 4, 5}
# 交集
print(set1.intersection(set2)) # 输出: {3}
# 差集
print(set1.difference(set2)) # 输出: {1, 2}