Python-Basic Day-3 python容器(字典、集合)

62 阅读6分钟

一、字典

1.1 字典的创建

# 1.空字典
empty_dict = {}
# 或
empty_dict = dict()

# 2.有初始值的字典
person = {
    "name": "Alice",
    "age": 25,
    "city": "New York"
}
# 或
person = dict(name="Bob", age=30, city="London")

# 3.为多个键设置相同的默认值-fromkeys()
keys = ["name", "age", "city"]
default_dict = dict.fromkeys(keys, "unknown")
print(default_dict)  # {'name': 'unknown', 'age': 'unknown', 'city': 'unknown'}

dict()函数还可以将包含双值子序列的序列转换成字典

lol = [ ['a', 'b'], ['c', 'd'], ['e', 'f'] ]
print(dict(lol))  # 输出:{'c': 'd', 'a': 'b', 'e': 'f'}

lot = [ ('a', 'b'), ('c', 'd'), ('e', 'f') ]
print(dict(lot))  # 输出:{'c': 'd', 'a': 'b', 'e': 'f'}

tol = ( ['a', 'b'], ['c', 'd'], ['e', 'f'] )
print(dict(tol))  # 输出:{'c': 'd', 'a': 'b', 'e': 'f'}

los = [ 'ab', 'cd', 'ef' ]
print(dict(los))  # 输出:{'c': 'd', 'a': 'b', 'e': 'f'}

1.2 字典的访问

person = {"name": "Alice", "age": 25, "city": "New York"}

# 1.直接访问
print(person["name"])  # Alice

# 2.使用 get() 方法(更安全,键不存在时返回 None 或默认值)
print(person.get("age"))        # 25
print(person.get("country"))    # None
print(person.get("country", "USA"))  # USA(设置默认值),但person字典不发生改变

这里涉及到判断键(key)是否存在,可用 in 或者 keys() 来判断

person = {"name": "Alice", "age": 25}

# 使用 in 关键字
if "name" in person:
    print("姓名:", person["name"])

# 使用 keys() 方法
if "age" in person.keys():
    print("年龄:", person["age"])

1.3 字典的修改

1.3.1 增加&修改操作

增添和修改操作都可以通过 [key]update() 实现

person = {"name": "Alice", "age": 25}

# 1.添加新键值对
person["city"] = "New York"
print(person)  # {'name': 'Alice', 'age': 26, 'city': 'New York'}

# 2. 修改值
person["city"] = "Suzhou"
print(person)  # {'name': 'Alice', 'age': 26, 'city': 'Suzhou'}

# 3.使用update()合并字典
my_dict = {'a': 1, 'b': 2}
others = {'b': 3, 'c': 4}
my_dict.update(others)

# 与此同时也修改了 my_dict['b']的值
print(my_dict)  # {'a': 1, 'b': 3, 'c': 4}

1.3.2 删除操作

person = {"name": "Alice", "age": 25, "city": "New York"}

# 1.使用 del 语句
del person["age"]
print(person)  # {'name': 'Alice', 'city': 'New York'}

# 2.使用 pop() 方法(删除并返回值)
city = person.pop("city")
print(city)    # New York
print(person)  # {'name': 'Alice'}

# 3.使用 popitem() 方法(删除并返回最后一个键值对)
person["age"] = 25
person["city"] = "New York"
last_item = person.popitem()
print(last_item)  # ('city', 'New York')
print(person)     # {'name': 'Alice', 'age': 25}

# 4.清空字典
person.clear()
print(person)  # {}

# 删除整个字典
del person

1.4 字典的常用方法

person = {"name": "Alice", "age": 25, "city": "New York"}

# keys() - 返回所有键
print(person.keys())        # dict_keys(['name', 'age', 'city'])

# values() - 返回所有值
print(person.values())      # dict_values(['Alice', 25, 'New York'])

# items() - 返回所有键值对 - 每一个键值对以元组的形式返回
print(person.items())       # dict_items([('name', 'Alice'), ('age', 25), ('city', 'New York')])

# copy() - 创建字典的浅拷贝
person_copy = person.copy()
print(person_copy)

# setdefault() - 如果键不存在,则设置默认值
person.setdefault("country", "USA")
print(person["country"])  # USA

1.5 字典遍历

person = {"name": "Alice", "age": 25, "city": "New York"}

# 遍历所有键
print("所有键:")
for key in person:
    print(key)

# 遍历所有值
print("\n所有值:")
for value in person.values():
    print(value)

# 遍历所有键值对
print("\n所有键值对:")
for key, value in person.items():
    print(f"{key}: {value}")

二、集合

集合是一个无序的、不重复元素的序列。它的主要特点是:

  • 无序性:元素没有固定的顺序
  • 互异性:元素不会重复
  • 确定性:元素必须是不可变类型

集合元素的要求

  • 必须是不可变数据类型(数字、字符串、元组等)
  • 不能是列表、字典、集合等可变类型

2.1 集合的创建

2.1.1 创建空集合

# 1.创建有元素的集合
fruits = {"apple", "banana", "orange"}
print(fruits)  # 输出可能是 {'banana', 'orange', 'apple'}(无序)

# 2.空集合(注意:不能使用 {},因为这是空字典)
empty_set = set()
print(empty_set)  # set()

2.1.2 用set()创建集合

# 1.从列表创建
numbers = set([1, 2, 3, 2, 1])  # 自动去重
print(numbers)  # {1, 2, 3}

# 2.从字符串创建(每个字符成为集合元素)
chars = set("hello")
print(chars)  # {'h', 'e', 'l', 'o'}(注意:只有一个 'l')

# 3.从元组创建
tuple_set = set((1, 2, 3, 2, 1))
print(tuple_set)  # {1, 2, 3}

# 4.从字典创建(只有key会被使用)
dict_set = set({'apple': 'red', 'orange': 'orange', 'cherry': 'red'})
print(dict_set)  # {'apple', 'cherry', 'orange'}

2.2 集合的基本操作

2.2.1 添加元素

fruits = {"apple", "banana"}

# 1.添加单个元素
fruits.add("orange")
print(fruits)  # {'apple', 'banana', 'orange'}

# 2.添加多个元素
fruits.update(["grape", "kiwi"])
print(fruits)  # {'apple', 'banana', 'orange', 'grape', 'kiwi'}

fruits.update({"mango", "pineapple"})
print(fruits)  # {'apple', 'banana', 'grape', 'pineapple', 'orange', 'mango', 'kiwi'}

2.2.2 删除元素

fruits = {"apple", "banana", "orange", "grape"}

# 1.remove() - 删除指定元素,如果元素不存在会报错
fruits.remove("banana")
print(fruits)  # {'apple', 'orange', 'grape'}

# 2.discard() - 删除指定元素,如果元素不存在不会报错
fruits.discard("orange")
fruits.discard("watermelon")  # 不会报错
print(fruits)  # {'apple', 'grape'}

# 3.pop() - 随机删除并返回一个元素 - 实测是从头到尾一个一个删除
item = fruits.pop()
print(f"删除的元素: {item}")
print(fruits)

# 4.clear() - 清空集合
fruits.clear()
print(fruits)  # set()

2.2.3 查询操作

fruits = {"apple", "banana", "orange"}

# 检查元素是否存在
print("apple" in fruits)    # True
print("grape" not in fruits)  # True

# 获取集合长度
print(len(fruits))  # 3

2.3 集合的数学运算

2.3.1 并集(Union)

set1 = {1, 2, 3}
set2 = {3, 4, 5}

# 方法一:使用 | 运算符
union_set = set1 | set2
print(union_set)  # {1, 2, 3, 4, 5}

# 方法二:使用 union() 方法
union_set = set1.union(set2)
print(union_set)  # {1, 2, 3, 4, 5}

# 多个集合的并集
set3 = {5, 6, 7}
multiple_union = set1 | set2 | set3
print(multiple_union)  # {1, 2, 3, 4, 5, 6, 7}

2.3.2 交集(Intersection)

set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}

# 方法一:使用 & 运算符
intersection_set = set1 & set2
print(intersection_set)  # {3, 4}

# 方法二:使用 intersection() 方法
intersection_set = set1.intersection(set2)
print(intersection_set)  # {3, 4}

# 多个集合的交集
set3 = {4, 5, 6}
multiple_intersection = set1 & set2 & set3
print(multiple_intersection)  # {4}

2.3.1 差集(Difference)

set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7}

# 方法一:使用 - 运算符
difference_set = set1 - set2
print(difference_set)  # {1, 2, 3}

# 方法二:使用 difference() 方法
difference_set = set1.difference(set2)
print(difference_set)  # {1, 2, 3}

# 对称差集(在 set1 或 set2 中,但不同时在两者中)
symmetric_difference = set1 ^ set2
# symmetric_difference()函数也可以
print(symmetric_difference)  # {1, 2, 3, 6, 7}

2.3.1 子集和超集

set1 = {1, 2, 3}
set2 = {1, 2, 3, 4, 5}
set3 = {1, 2, 6}

# 子集检查
print(set1 <= set2)  # True,set1 是 set2 的子集
print(set1.issubset(set2))  # True

# 真子集检查
print(set1 < set2)   # True,set1 是 set2 的真子集

# 超集检查
print(set2 >= set1)  # True,set2 是 set1 的超集
print(set2.issuperset(set1))  # True

# 真超集检查
print(set2 > set1)   # True,set2 是 set1 的真超集

# 无交集检查
print(set1.isdisjoint(set3))  # False,有交集 {1, 2}

2.4 集合的应用

2.4.1 数据去重

def remove_duplicates(data):
    """去除列表中的重复元素"""
    return list(set(data))

# 保持顺序的去重
def remove_duplicates_ordered(data):
    seen = set()
    result = []
    for item in data:
        if item not in seen:
            seen.add(item)
            result.append(item)
    return result

2.4.2 找共同元素

def find_common_elements(*lists):
    """查找多个列表中的共同元素"""
    if not lists:
        return []
    
    # 将第一个列表转换为集合
    common = set(lists[0])
    
    # 与后续列表求交集
    for lst in lists[1:]:
        common &= set(lst)
    
    return list(common)

# 测试查找共同元素
list1 = [1, 2, 3, 4, 5]
list2 = [3, 4, 5, 6, 7]
list3 = [5, 6, 7, 8, 9]

common = find_common_elements(list1, list2, list3)
print(f"共同元素: {common}")  # [5]