面向初学者的 Python(数据结构:字典和集合)

360影视 2025-02-02 13:17 2

摘要:# Creating a dictionaryperson = { "name": "Alice", "age": 25, "is_student": True}print(person) # Output: {'name': 'Alice', 'age':

字典是项的无序集合,其中每个项都是一个键值对。字典是可变的,这意味着它们的内容可以在创建后更改。

可以通过将键值对放在大括号内来创建字典,大括号 {} 以逗号分隔。每个键与其值之间用冒号分隔 : 。

# Creating a dictionaryperson = { "name": "Alice", "age": 25, "is_student": True}print(person) # Output: {'name': 'Alice', 'age': 25, 'is_student': True}

字典项目使用其键进行访问。

print(person["name"]) # Output: Aliceprint(person["age"]) # Output: 25print(person["is_student"]) # Output: True

由于字典是可变的,因您可以更改其值、添加新的键值对或删除现有键值对。

# Modifying an existing itemperson["age"] = 26print(person) # Output: {'name': 'Alice', 'age': 26, 'is_student': True}# Adding a new itemperson["city"] = "New York"print(person) # Output: {'name': 'Alice', 'age': 26, 'is_student': True, 'city': 'New York'}# Removing an itemdel person["is_student"]print(person) # Output: {'name': 'Alice', 'age': 26, 'city': 'New York'}

字典有几种内置方法,允许对它们执行操作。

person = { "name": "Alice", "age": 25, "is_student": True}# Getting all keyskeys = person.keysprint(keys) # Output: dict_keys(['name', 'age', 'is_student'])# Getting all valuesvalues = person.valuesprint(values) # Output: dict_values(['Alice', 25, True])# Getting all itemsitems = person.itemsprint(items) # Output: dict_items([('name', 'Alice'), ('age', 25), ('is_student', True)])# Checking if a key existshas_age = "age" in personprint(has_age) # Output: True# Removing all itemsperson.clearprint(person) # Output: {}

可以通过将项目放在大括号 {} 内 ,用逗号分隔,或使用该 set 函数来创建集合。

# Creating a setfruits = {"apple", "banana", "cherry"}print(fruits) # Output: {'apple', 'banana', 'cherry'}# Creating a set using the set functionnumbers = set([1, 2, 3, 4, 5])print(numbers) # Output: {1, 2, 3, 4, 5}

由于集合是可变的,因此可以添加和删除项目。

# Adding an itemfruits.add("orange")print(fruits) # Output: {'apple', 'banana', 'cherry', 'orange'}# Removing an itemfruits.remove("banana")print(fruits) # Output: {'apple', 'cherry', 'orange'}

集合支持多种数学运算,例如并集、交集和差分。

set1 = {1, 2, 3}set2 = {3, 4, 5}# Union: combining both setsunion = set1.union(set2)print(union) # Output: {1, 2, 3, 4, 5}# Intersection: items present in both setsintersection = set1.intersection(set2)print(intersection) # Output: {3}# Difference: items present in set1 but not in set2difference = set1.difference(set2)print(difference) # Output: {1, 2}词典:当您需要存储相关数据对(例如一个人的姓名和年龄)时,请使用词典。词典非常适合基于唯一键进行快速查找和分配。集合:当您需要存储唯一项目并执行并集、交集和差值等数学运算时,请使用集合。集合是管理独特元素集合的理想选择。

来源:自由坦荡的湖泊AI

相关推荐