Python数据结构详解:字典、列表、元组、集合与字符串的使用

在Python编程中,掌握各种数据结构的使用方法是至关重要的。本文将详细介绍字典、列表、元组、集合和字符串的创建方式、实例应用、特点以及它们之间的区别,帮助你在实际开发中更高效地选择和使用这些数据结构。

一、列表(list)

(一)创建方式

列表是Python中最常用的数据结构之一,它是一个有序的元素序列,可以包含不同类型的元素。创建列表非常简单,只需要将元素用方括号[]括起来,并用逗号分隔即可。如果要创建一个空列表,只需写空列表 = []

# 创建一个包含多种类型元素的列表
mixed_list = [1, "hello", 3.14, True]
# 创建一个空列表
empty_list = []

(二)特点

列表具有以下特点:

  1. 有序:列表中的元素是有顺序的,可以通过索引来访问特定位置的元素。

  2. 可变:列表的大小和内容可以随时修改,例如添加、删除或修改元素。

  3. 允许重复:列表中可以有重复的元素。

  4. 类型灵活:列表中的元素可以是不同数据类型。

(三)列表的常见方法

方法名 说明 参数说明 返回值 示例代码及输出
列表.append(元素) 向列表中追加一个元素 元素:要添加的元素 None fruits = ["apple", "banana"]\
fruits.append("cherry")
print(fruits) 输出:["apple", "banana", "cherry"]
列表.extend(容器) 将数据容器的内容依次取出,追加到列表尾部 容器:可迭代对象(如列表、元组等) None fruits = ["apple", "banana"]
fruits.extend(["cherry", "orange"])
print(fruits) 输出:["apple", "banana", "cherry", "orange"]
列表.insert(下标, 元素) 在指定下标处,插入指定的元素 下标:插入位置索引
元素:要插入的元素
None fruits = ["apple", "banana"]
fruits.insert(1, "cherry")
print(fruits) 输出:["apple", "cherry", "banana"]
del 列表[下标] 删除列表指定下标元素 下标:要删除元素的索引 None fruits = ["apple", "banana", "cherry"]
del fruits[1]
print(fruits) 输出:["apple", "cherry"]
列表.pop(下标) 删除列表指定下标元素 下标:要删除元素的索引(可选,默认为最后一个元素) 被删除的元素 fruits = ["apple", "banana", "cherry"]
popped = fruits.pop(1)
print(fruits) 输出:["apple", "cherry"]
print(popped) 输出:banana
列表.remove(元素) 从前向后,删除此元素第一个匹配项 元素:要删除的元素 None fruits = ["apple", "banana", "apple"]
fruits.remove("apple")
print(fruits) 输出:["banana", "apple"]
列表.clear() 清空列表 None fruits = ["apple", "banana", "cherry"]
fruits.clear()
print(fruits) 输出:[]
列表.count(元素) 统计此元素在列表中出现的次数 元素:要统计的元素 出现次数 fruits = ["apple", "banana", "apple"]
count = fruits.count("apple")
print(count) 输出:2
列表.index(元素) 查找指定元素在列表的下标,找不到报错ValueError 元素:要查找的元素 下标 fruits = ["apple", "banana", "cherry"]
index = fruits.index("banana")
print(index) 输出:1
len(列表) 统计容器内有多少元素 列表:要统计的列表 元素数量 fruits = ["apple", "banana", "cherry"]
length = len(fruits)
print(length) 输出:3

(四)实例应用

列表适用于需要频繁修改和访问元素的场景,比如存储一组数据并进行排序、筛选等操作。

# 访问列表元素
fruits = ["apple", "banana", "cherry"]
print(fruits[0])  # 输出:apple

# 修改列表元素
fruits[1] = "orange"
print(fruits)  # 输出:['apple', 'orange', 'cherry']

# 添加元素到列表
fruits.append("grape")
print(fruits)  # 输出:['apple', 'orange', 'cherry', 'grape']

# 删除列表元素
del fruits[0]
print(fruits)  # 输出:['orange', 'cherry', 'grape']

# 列表切片
print(fruits[1:3])  # 输出:['cherry', 'grape']

# 遍历列表
for fruit in fruits:
    print(fruit)

# 列表排序
numbers = [3, 1, 4, 1, 5, 9, 2]
numbers.sort()
print(numbers)  # 输出:[1, 1, 2, 3, 4, 5, 9]

# 列表长度
print(len(numbers))  # 输出:7

二、元组(tuple)

(一)创建方式

元组与列表类似,也是一个有序的元素序列,但元组是不可变的。创建元组时,将元素用圆括号()括起来,元素之间用逗号分隔。空元组的创建方式是空元组 = ()

# 创建一个元组
coordinates = (3, 5)
# 创建一个空元组
empty_tuple = ()

(二)特点

元组的特点包括:

  1. 有序:可以通过索引来访问元素。

  2. 不可变:元组的大小和内容一旦创建就不能修改。

  3. 元素可为不同数据类型。

(三)元组的常见操作

操作名 说明 参数说明 返回值 示例代码及输出
元组[下标] 根据下标访问元组中的元素 下标:元素的位置索引 元素值 t = (1, 2, 3)
print(t[1]) 输出:2
元组.index(元素) 查找元素在元组中的索引位置,若不存在则报错ValueError 元素:要查找的元素 索引值 t = (1, 2, 3)
print(t.index(2)) 输出:1
元组.count(元素) 统计元素在元组中出现的次数 元素:要统计的元素 出现次数 t = (1, 2, 2, 3)
print(t.count(2)) 输出:2
len(元组) 获取元组中元素的数量 元组:要获取长度的元组 元素数量 t = (1, 2, 3)
print(len(t)) 输出:3
元组 + 元组 将两个元组连接成一个新的元组 另一个元组 新元组 t1 = (1, 2)
t2 = (3, 4)
t3 = t1 + t2
print(t3) 输出:(1, 2, 3, 4)
元组 * 倍数 将元组重复指定倍数生成一个新的元组 倍数:整数 新元组 t = (1, 2)
print(t * 3) 输出:(1, 2, 1, 2, 1, 2)
元组[起始:结束:步长] 对元组进行切片操作,获取指定范围的元素 起始:起始索引(可选)
结束:结束索引(可选)
步长:步长值(可选)
新元组 t = (0, 1, 2, 3, 4)
print(t[1:4]) 输出:(1, 2, 3)
print(t[::2]) 输出:(0, 2, 4)

(四)实例应用

元组适用于存储一组固定不变的数据,比如坐标点、日期等。

# 访问元组元素
print(coordinates[0])  # 输出:3

# 元组解包
x, y = coordinates
print(x, y)  # 输出:3 5

# 遍历元组
for num in coordinates:
    print(num)

# 元组长度
print(len(coordinates))  # 输出:2

三、字典(dict)

(一)创建方式

字典是一个无序的键值对集合,每个键值对由冒号:分隔,整个字典用大括号{}括起来。创建空字典的方式是空字典 = {}

# 创建一个字典
person = {"name": "Alice", "age": 25, "city": "New York"}
# 创建一个空字典
empty_dict = {}

(二)特点

字典具有以下特点:

  1. 无序:字典中的键值对没有固定的顺序。

  2. 可变:可以随时添加、删除或修改键值对。

  3. 键唯一:每个键在字典中必须是唯一的。

  4. 键不可变:键必须是不可变类型,如字符串、数字或元组。

(三)字典的常见方法

方法名 说明 参数说明 返回值 示例代码及输出
字典.keys() 获取字典中所有键 视图对象(可迭代) person = {"name": "Alice", "age": 25}
keys = person.keys()
print(list(keys)) 输出:['name', 'age']
字典.values() 获取字典中所有值 视图对象(可迭代) person = {"name": "Alice", "age": 25}
values = person.values()
print(list(values)) 输出:['Alice', 25]
字典.items() 获取字典中所有的键值对 视图对象(可迭代) person = {"name": "Alice", "age": 25}
items = person.items()
print(list(items)) 输出:[('name', 'Alice'), ('age', 25)]
字典.get(键, 默认值) 获取指定键的值,如果键不存在,返回默认值 键:要查找的键
默认值:键不存在时返回的值(可选)
键对应的值或默认值 person = {"name": "Alice"}
age = person.get("age", 0)
print(age) 输出:0
字典.pop(键) 删除并返回指定键的值 键:要删除的键 被删除的值 person = {"name": "Alice", "age": 25}
age = person.pop("age")
print(age) 输出:25
print(person) 输出:{"name": "Alice"}
字典.popitem() 删除并返回字典中的最后一个键值对 被删除的键值对 person = {"name": "Alice", "age": 25}
item = person.popitem()
print(item) 输出:("age", 25)
print(person) 输出:{"name": "Alice"}
字典.update(其他字典) 将其他字典的键值对更新到当前字典中 其他字典:要合并的字典 None person = {"name": "Alice"}
person.update({"age": 25})
print(person) 输出:{"name": "Alice", "age": 25}
字典.setdefault(键, 默认值) 如果键存在,返回其值;否则插入键并设置为默认值 键:要查找的键
默认值:键不存在时设置的值(可选)
键对应的值或默认值 person = {"name": "Alice"}
age = person.setdefault("age", 25)
print(age) 输出:25
print(person) 输出:{"name": "Alice", "age": 25}
字典.clear() 清空字典 None person = {"name": "Alice", "age": 25}
person.clear()
print(person) 输出:{}

(四)实例应用

字典常用于根据键快速查找对应的值,比如存储用户信息、配置参数等。

# 访问字典值
print(person["name"])  # 输出:Alice

# 添加键值对
person["email"] = "[email protected]"
print(person)  # 输出:{'name': 'Alice', 'age': 25, 'city': 'New York', 'email': '[email protected]'}

# 修改字典值
person["age"] = 26
print(person)  # 输出:{'name': 'Alice', 'age': 26, 'city': 'New York', 'email': '[email protected]'}

# 删除键值对
del person["city"]
print(person)  # 输出:{'name': 'Alice', 'age': 26, 'email': '[email protected]'}

# 遍历字典
for key in person:
    print(key, person[key])

# 获取字典的键、值和键值对
print(person.keys())   # 输出:dict_keys(['name', 'age', 'email'])
print(person.values()) # 输出:dict_values(['Alice', 26, '[email protected]'])
print(person.items())  # 输出:dict_items([('name', 'Alice'), ('age', 26), ('email', '[email protected]')])

四、集合(set)

(一)创建方式

集合是一个无序且不重复的元素集合,用于存储唯一的元素。创建集合时,将元素用大括号{}括起来,或者使用set()函数。创建空集合必须使用空集合 = set(),因为{}会被识别为空字典。

# 创建一个集合
unique_numbers = {1, 2, 3, 4, 5}
# 创建一个空集合
empty_set = set()

(二)特点

集合的特点包括:

  1. 无序:元素没有固定的顺序。

  2. 不可重复:集合中的元素是唯一的。

  3. 可变:可以添加或删除元素。

(三)集合的常见方法

方法名 说明 参数说明 返回值 示例代码及输出
集合.add(元素) 集合内添加一个元素 元素:要添加的元素 None s = {1, 2}
s.add(3)
print(s) 输出:{1, 2, 3}
集合.remove(元素) 移除集合内指定的元素 元素:要移除的元素 None s = {1, 2, 3}
s.remove(2)
print(s) 输出:{1, 3}
集合.discard(元素) 移除集合内指定的元素,若元素不存在,不报错 元素:要移除的元素 None s = {1, 2, 3}
s.discard(4)
print(s) 输出:{1, 2, 3}
集合.pop() 从集合中随机取出一个元素 被取出的元素 s = {1, 2, 3}
popped = s.pop()
print(popped) 输出:1(可能因集合无序而不同)
print(s) 输出:{2, 3}
集合.clear() 将集合清空 None s = {1, 2, 3}
s.clear()
print(s) 输出:set()
集合1.difference(集合2) 得到一个新集合,内含2个集合的差集,原有的2个集合内容不变 集合2:另一个集合 新集合 s1 = {1, 2, 3}
s2 = {3, 4, 5}
diff = s1.difference(s2)
print(diff) 输出:{1, 2}
集合1.difference_update(集合2) 在集合1中,删除集合2中存在的元素,集合1被修改,集合2不变 集合2:另一个集合 None s1 = {1, 2, 3}
s2 = {3, 4, 5}
s1.difference_update(s2)
print(s1) 输出:{1, 2}
集合1.union(集合2) 得到一个新集合,内含2个集合的全部元素,原有的2个集合内容不变 集合2:另一个集合 新集合 s1 = {1, 2}
s2 = {3, 4}
union = s1.union(s2)
print(union) 输出:{1, 2, 3, 4}
集合1.update(集合2) 将集合2的元素添加到集合1中,集合1被修改,集合2不变 集合2:另一个集合 None s1 = {1, 2}
s2 = {3, 4}
s1.update(s2)
print(s1) 输出:{1, 2, 3, 4}
集合1.intersection(集合2) 得到一个新集合,内含2个集合的共有元素,原有的2个集合内容不变 集合2:另一个集合 新集合 s1 = {1, 2, 3}
s2 = {3, 4, 5}
inter = s1.intersection(s2)
print(inter) 输出:{3}
集合1.intersection_update(集合2) 修改集合1,保留集合2中存在的元素,集合1被修改,集合2不变 集合2:另一个集合 None s1 = {1, 2, 3}
s2 = {3, 4, 5}
s1.intersection_update(s2)
print(s1) 输出:{3}
集合1.issubset(集合2) 判断集合1是否是集合2的子集 集合2:另一个集合 布尔值(是返回True,否返回False s1 = {1, 2}
s2 = {1, 2, 3}
is_sub = s1.issubset(s2)
print(is_sub) 输出:True
集合1.issuperset(集合2) 判断集合1是否是集合2的超集 集合2:另一个集合 布尔值(是返回True,否返回False s1 = {1, 2, 3}
s2 = {1, 2}
is_super = s1.issuperset(s2)
print(is_super) 输出:True
len(集合) 统计集合内有多少元素 集合:要统计的集合 元素数量 s = {1, 2, 3}
length = len(s)
print(length) 输出:3

(四)实例应用

集合适用于需要去重或进行集合运算(如交集、并集)的场景。

# 添加元素到集合
unique_numbers.add(6)
print(unique_numbers)  # 输出:{1, 2, 3, 4, 5, 6}

# 删除集合元素
unique_numbers.remove(1)
print(unique_numbers)  # 输出:{2, 3, 4, 5, 6}

# 集合运算
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}(差集)

# 遍历集合
for num in unique_numbers:
    print(num)

# 集合长度
print(len(unique_numbers))  # 输出:5

五、字符串(str)

(一)创建方式

字符串是由字符组成的序列,用于表示文本数据。创建字符串时,可以用单引号''、双引号""或三引号''' '''(用于多行字符串)。空字符串的创建方式是空字符串 = ""

# 创建字符串
greeting = "Hello, World!"
# 创建多行字符串
multi_line = """This is a
multi-line string."""
# 创建空字符串
empty_str = ""

(二)特点

字符串的特点:

  1. 不可变:字符串一旦创建,内容不能修改,但可以基于原字符串创建新字符串。

  2. 有序:可以通过索引访问特定位置的字符。

  3. 支持多种编码:如ASCII、Unicode等。

(三)字符串的常见方法

方法名 说明 参数说明 返回值 示例代码及输出
字符串[下标] 根据下标索引取出特定位置字符 下标:字符位置索引 字符 s = "hello"
print(s[1]) 输出:e
字符串.index(子字符串) 查找子字符串在字符串中的第一个匹配项的起始下标,找不到报错ValueError 子字符串:要查找的字符串 下标 s = "hello"
index = s.index("l")
print(index) 输出:2
字符串.find(子字符串) 查找子字符串在字符串中的第一个匹配项的起始下标,找不到返回-1 子字符串:要查找的字符串 下标或-1 s = "hello"
index = s.find("x")
print(index) 输出:-1
字符串.replace(旧子字符串, 新子字符串) 将字符串内的全部旧子字符串替换为新子字符串,不会修改原字符串,而是得到一个新的字符串 旧子字符串:要被替换的字符串
新子字符串:替换后的字符串
新字符串 s = "hello"
new_s = s.replace("l", "x")
print(new_s) 输出:hexo
print(s) 输出:hello
字符串.split(分隔符) 按照分隔符将字符串分割成多个子字符串,返回一个列表,不会修改原字符串,而是得到一个新的列表 分隔符:分割的依据(默认为空格) 列表 s = "hello world"
parts = s.split()
print(parts) 输出:["hello", "world"]
print(s) 输出:hello world
字符串.strip([字符集]) 移除字符串首尾的空格、换行符或指定的字符集,默认移除首尾的空白字符 字符集:要移除的字符集合(可选) 新字符串 s = " hello "
new_s = s.strip()
print(new_s) 输出:hello
字符串.lstrip([字符集]) 移除字符串左侧的空格、换行符或指定的字符集,默认移除左侧的空白字符 字符集:要移除的字符集合(可选) 新字符串 s = " hello "
new_s = s.lstrip()
print(new_s) 输出:hello
字符串.rstrip([字符集]) 移除字符串右侧的空格、换行符或指定的字符集,默认移除右侧的空白字符 字符集:要移除的字符集合(可选) 新字符串 s = " hello "
new_s = s.rstrip()
print(new_s) 输出: hello
字符串.count(子字符串) 统计字符串内某子字符串的出现次数 子字符串:要统计的字符串 出现次数 s = "hello"
count = s.count("l")
print(count) 输出:2
字符串.upper() 将字符串中的小写字母转换为大写 新字符串 s = "hello"
upper_s = s.upper()
print(upper_s) 输出:HELLO
字符串.lower() 将字符串中的大写字母转换为小写 新字符串 s = "HELLO"
lower_s = s.lower()
print(lower_s) 输出:hello
字符串.capitalize() 将字符串的第一个字符转换为大写,其余转换为小写 新字符串 s = "hELLO"
cap_s = s.capitalize()
print(cap_s) 输出:Hello
字符串.title() 将字符串中每个单词的首字母转换为大写 新字符串 s = "hello world"
title_s = s.title()
print(title_s) 输出:Hello World
字符串.startswith(子字符串) 检查字符串是否以指定的子字符串开头 子字符串:要检查的字符串 布尔值(是返回True,否返回False s = "hello"
starts = s.startswith("he")
print(starts) 输出:True
字符串.endswith(子字符串) 检查字符串是否以指定的子字符串结尾 子字符串:要检查的字符串 布尔值(是返回True,否返回False s = "hello"
ends = s.endswith("lo")
print(ends) 输出:True
字符串.join(可迭代对象) 将可迭代对象中的元素用字符串连接成一个新字符串 可迭代对象:包含字符串的元素的可迭代对象 新字符串 parts = ["hello", "world"]
s = " ".join(parts)
print(s) 输出:hello world
字符串.format(*args, **kwargs) 格式化字符串,将参数插入到字符串中的占位符位置 *args:位置参数
**kwargs:关键字参数
新字符串 s = "My name is {} and I'm {} years old".format("Alice", 25)
print(s) 输出:My name is Alice and I'm 25 years old
f字符串 使用f-string进行格式化,将表达式嵌入到字符串中 表达式:要嵌入的表达式 新字符串 name = "Alice"
age = 25
s = f"My name is {name} and I'm {age} years old"
print(s) 输出:My name is Alice and I'm 25 years old
len(字符串) 统计字符串的字符个数 字符串:要统计的字符串 字符数量 s = "hello"
length = len(s)
print(length) 输出:5

(四)实例应用

字符串用于处理文本数据,如文件操作、用户输入输出等。

# 访问字符串字符
print(greeting[0])  # 输出:H

# 字符串拼接
full_name = "John " + "Doe"
print(full_name)  # 输出:John Doe

# 字符串格式化
formatted = f"Hello, {full_name}!"
print(formatted)  # 输出:Hello, John Doe!

# 字符串长度
print(len(greeting))  # 输出:13

# 字符串切片
print(greeting[0:5])  # 输出:Hello

# 遍历字符串
for char in greeting:
    print(char)

# 字符串方法
print(greeting.lower())  # 输出:hello, world!
print(greeting.upper())  # 输出:HELLO, WORLD!
print(greeting.replace("Hello", "Hi"))  # 输出:Hi, World!

六、数据结构之间的区别

为了更清晰地理解这些数据结构,以下是它们之间的主要区别:

特性 列表(list) 元组(tuple) 字典(dict) 集合(set) 字符串(str)
有序
可变
元素唯一性 是(键唯一)
主要用途 存储有序可变序列 存储固定数据 键值对存储 唯一元素集合 文本数据存储

七、总结

在Python中,列表、元组、字典、集合和字符串各有其独特的用途和特点:

  • 列表适合存储有序且可变的元素序列。

  • 元组用于存储固定不变的有序数据。

  • 字典提供高效的键值对存储和查找。

  • 集合用于存储唯一的元素,并支持集合运算。

  • 字符串用于处理文本数据。

你可能感兴趣的:(python,开发语言)