三、数据类型全解析
Python 作为一种动态类型语言,拥有丰富多样的数据类型,每种类型都有其独特的特性和应用场景。本文将系统介绍 Python 的六种主要数据类型(数字、字符串、元组、列表、字典、集合),并详细讲解常用的数据类型转换函数。
文章目录
-
一、Python的六大数据类型
-
二、序列
-
三、Number (数字类型)
- 1、整数 (int)
- 2、浮点数 (float)
- 3、复数 (complex)
- 数字运算示例
-
四、String (字符串类型)
- 1、字符串创建
- 2、字符串索引与切片
- 3、常用字符串方法
- 4、字符串格式化
-
五、Tuple (元组类型)
- 1、创建元组
- 2、元组操作
- 3、元组特点
-
六、List (列表类型)
- 1、创建列表
- 2、列表操作
- 3、列表排序
-
七、Dictionary (字典类型)
- 1、创建字典
- 2、字典操作
- 3、字典排序
-
八、Set (集合类型)
- 1、创建集合
- 2、集合操作
-
九、数据类型转换函数
- 1、转换为数字
- 2、转换为字符串
- 3、转换为序列类型
- 4、转换为字典
- 5、类型判断函数
-
十、类型转换实战示例
-
十一、总结
一、Python的六大数据类型
Python的数据类型可以分为以下几大类:
1、数字类型(Number):包括整数、浮点数、复数等
2、序列类型:
- 字符串(String):不可变的字符序列
- 列表(List):可变的字符序列
- 元组(Tuple):不可变的字符序列
3、映射类型:字典(Dictionary):键值对的无序集合
4、集合类型:集合(Set):无序不重复元素的集合
5、布尔类型(Boolean):True/False(实际上是int的子类)
6、None类型:表示空值的特殊类型
其中,最常用且核心的是数字、字符串、元组、列表、字典和集合这六种类型。
二、序列
1、什么是序列
序列(Sequence)是一种基本且核心的数据结构,它允许我们以有序的方式存储和操作数据。序列可以包含不同类型的元素,并且支持通过索引来访问和修改这些元素。
常见的序列类型包括:列表(List)、元组(Tuple)、字符串(String)。
2、序列的操作
索引:sequence[0]
切片:sequence[1:3]
相加:sequence1 + sequence2
乘法:sequence * 3
检查成员:x in sequence
计算长度:len(sequence)
计算最大值、最小值:max(sequence)、min(sequence)
三、Number(数字类型)
Python支持三种数值类型:
1、整数(int)
a = 10 # 十进制
b = 0b1010 # 二进制,值为10
c = 0o12 # 八进制,值为10
d = 0xA # 十六进制,值为10
2、浮点数(float)
x = 3.14
y = 1.23e-4 # 科学计数法,0.000123
3、复数(complex)
z = 2 + 3j # 实部2,虚部3
print(z.real) # 2.0
print(z.imag) # 3.0
数字运算示例
# 基本运算
print(5 + 3) # 加法
print(5 - 3) # 减法
print(5 * 3) # 乘法
print(5 / 3) # 除法,结果为浮点数1.666...
print(5 // 3) # 整除,结果为1
print(5 % 3) # 取模,结果为2
print(5 ** 3) # 幂运算,125
# 内置数学函数
import math
print(abs(-5)) # 绝对值
print(round(3.14159, 2)) # 四舍五入
print(math.sqrt(16)) # 平方根
print(math.pi) # 圆周率
四、String(字符串类型)
1、定义:
字符串是不可变的、有序的。
字符串中元素不可修改。
字符串使用单引号、双引号或三重引号定义。
字符串中每个值都有对应的位置值,称为索引或下标,索引从起始从0开始向后逐个递增,并且从末尾从-1开始逐个向前递减。
2、创建字符串
str1 = "hello world"
3、访问字符串
s = "Python"
print(s[0]) # 'P'
print(s[-1]) # 'n'
print(s[1:4]) # 'yth'
print(s[:3]) # 'Pyt'
print(s[3:]) # 'hon'
print(s[::-1]) # 'nohtyP' (反转)
print(s[::-2]) # 'Pto' (步长为2)
4、字符串相加
str1 = "hello world"
str2 = "dlrow olleh"
print(str1 + str2) # hello worlddlrow olleh
5、检查成员是否为字符串中元素
str1 = "hello world"
print("lo" in str1) # True
6、常用函数
| 函数 | 说明 |
|---|---|
| str.replace(old, new[, max]) | 把将字符串中的 old 替换成 new,如果指定 max,则替换不超过 max 次 |
| str.split([x][, n]) | 按 x 分隔字符串,默认按任何空白字符串分隔并在结果中丢弃空字符串。可指定最大分隔次数 |
| str.rsplit([x][, n]) | 与 split() 类似,从右边开始分隔 |
| x.join(seq) | 以 x 作为分隔符,将序列中所有的字符串合并为一个新的字符串 |
| str.strip([x]) | 截掉字符串两边的空格或指定字符 |
| str.lstrip([x]) | 截掉字符串左边的空格或指定字符 |
| str.rstrip([x]) | 截掉字符串右边的空格或指定字符 |
| str.removeprefix(x) | 截掉字符串指定前缀 |
| str.removesuffix(x) | 截掉字符串指定后缀 |
| str.upper() | 将所有字符串转为大写 |
| str.lower() | 将所有字符串转为小写 |
| str.swapcase() | 反转字符串中字母大小写 |
| str.capitalize() | 将字符串第一个字母变为大写,其他字母变为小写 |
| str.title() | 将字符串每个单词首字母大写 |
| str.casefold() | 返回适合无大小写比较的字符串版本 |
| len(str) | 返回字符串长度 |
| max(str) | 返回字符串中最大值 |
| min(str) | 返回字符串中最小值 |
| str.find(x[, start][, end]) | 返回字符串中第一个 x 的索引值,不存在则返回 -1,可指定字符串开始结束范围 |
| str.rfind(x[, start][, end]) | 与 find() 类似,从右边开始查找 |
| str.index(x[, start][, end]) | 返回字符串中第一个 x 的索引值,不存在则报错,可指定字符串开始结束范围 |
| str.rindex(x[, start][, end]) | 与 index() 类似,从右边开始查找 |
| str.count(x[, start][, end]) | 返回字符串中 x 的个数,可指定字符串开始结束范围 |
五、Tuple(元组类型)
1、定义:
元组是一个不可变的、有序的元素集合。
不能对元组中的元素进行修改操作。
元组使用 () 定义,数据之间使用,分隔。
元组中每个元素都有对应的位置值,称为索引或下标,索引从起始从0开始向后逐个递增,并且从末尾从-1开始逐个向前递减。
元组中元素可以是不同的类型。
元组的使用方式与列表类似。
2、创建元组
t1 = (1, 2, 3)
t2 = 1, 2, 3 # 括号可省略
t3 = (5,) # 单元素元组需要逗号
t4 = tuple([1, 2, 3]) # 从其他序列转换
3、元组操作
# 访问元组
tuple1 = (100, 200, 300, 400, 500)
print(tuple1[2])
print(tuple1[-1])
print(tuple1[2:4])
# 元组相加
tuple1 = (100, 200, 300)
tuple2 = ("a", "b", "c")
print(tuple1 + tuple2) # (100, 200, 300, 'a', 'b', 'c')
# 元组乘法
tuple1 = (100, 200, 300)
print(tuple1 * 2) # (100, 200, 300, 100, 200, 300)
# 检查成员是否为元组中元素
tuple1 = (100, 200, 300, 400, 500)
print(300 in tuple1) # True
# 获取元组长度
tuple1 = (100, 200, 300, 400, 500)
print(len(tuple1)) # 5
# 求元组中元素的最大值、最小值、加和
tuple1 = (100, 200, 300, 400, 500)
print(max(tuple1)) # 500
print(min(tuple1)) # 100
print(sum(tuple1)) # 1500
# 遍历元组
tuple1 = (100, 200, 300, 400, 500)
for i in tuple1:
print(i)
for i in range(len(tuple1)):
print(i, tuple1[i])
for i, val in enumerate(tuple1):
print(i, val)
4、元组特点
- 不可变性:创建后不能修改元素
- 安全性:适合存储不应被修改的数据
- 性能:比列表更高效,适合作为字典键
六、List(列表类型)
1、定义:
列表是一个可变的、有序的元素集合。
列表使用 [] 定义,数据之间使用 , 分隔。
列表中每个元素都有对应的位置值,称为索引或下标,索引从起始从0开始向后逐个递增,并且从末尾从-1开始逐个向前递减。
列表中元素可以是不同的类型。
2、创建列表
list1 = [100, 200, 300, 400, 500]
3、列表操作
3.1、通过索引获取列表中元素
list1 = [100, 200, 300, 400, 500]
print(list1[1]) # 200
print(list1[-2]) # 400
3.2、列表切片
list1 = [100, 200, 300, 400, 500]
print(list1) # 取全部元素
print(list1[:]) # 复制整个列表
print(list1[2:4]) # 取索引从2开始到4(不包含)的元素
print(list1[2:]) # 取索引从2开始到末尾的元素
print(list1[:2]) # 取索引从0开始到2(不包含)的元素
print(list1[2:-1]) # 取索引从2开始到-1(不包含)的元素
print(list1[::-1]) # 倒序取元素
3.3、向列表中添加元素
list1 = [100, 200, 300, 400, 500]
list1.append(600) # 在列表末尾追加元素
list1.insert(2,700) # 在列表指定的位置追加元素
print(list1)
3.4、列表相加
list1 = [100, 200, 300]
list2 = ["a", "b", "c"]
print(list1 + list2) # [100, 200, 300, 'a', 'b', 'c']
3.5、列表乘法
list1 = [100, 200, 300]
print(list1 * 2) # [100, 200, 300, 100, 200, 300]
3.6、 修改列表中元素
# 通过下标修改
list1 = [100, 200, 300, 400, 500]
list1[0] = -1
print(list1)
# 通过切片修改
list1 = [100, 200, 300, 400, 500]
list1[2:4] = ["a", "b", "c"]
print(list1)
3.7、检查成员是否为列表中元素
list1 = [100, 200, 300]
print(100 in list1) # True
3.8、获取列表长度
list1 = [100, 200, 300]
print(len(list1)) # 3
3.9、求列表中元素的最大值、最小值、加和
list1 = [100, 200, 300, 400, 500]
print(max(list1)) # 500
print(min(list1)) # 100
print(sum(list1)) # 1500
4.0、 遍历列表
# 直接遍历列表元素
list1 = [100, 200, 300, 400, 500]
for i in list1:
print(i)
# 通过下标遍历列表
list1 = [100, 200, 300, 400, 500]
for i in range(len(list1)):
print(i, list1[i])
#使用 enumerate() 同时获取列表的下标和元素
list1 = [100, 200, 300, 400, 500]
for i, val in enumerate(list1):
print(i, val)
4.1、删除列表指定位置元素或者切片
list1 = [100, 200, 300, 400, 500]
del list1[2]
print(list1)
4.2、 嵌套列表
# 列表中元素可以为列表
list1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
for inner_list in list1:
print(inner_list)
4、列表推导式
# 基础的列表推导式
squares = [x**2 for x in range(5)]
print(squares) # [0, 1, 4, 9, 16]
# 带条件的列表推导式
squares = [x**2 for x in range(10) if x % 2 == 0]
print(squares) # [0, 4, 16, 36, 64]
# 使用现有列表的列表推导式
list1 = [1, 2, 3, 4, 5]
squares = [x**2 for x in list1]
print(squares) # [1, 4, 9, 16, 25]
# 包含多个循环的列表推导式
list1 = [1, 2, 3, 4, 5]
list2 = ["a", "b", "c", "d", "e"]
tuple_list = [(i, j) for i in list1 for j in list2]
print(tuple_list)
5、常用函数
| 函数 | 说明 |
|---|---|
| list.insert(index,x) | 在指定位置插入 x |
| list.append(x) | 在列表末尾追加 x |
| list1.extend(list2) | 在列表 1 的末尾追加列表 2 的数据 |
| del list[index] | 删除指定位置的数据或切片 |
| list.remove(x) | 删除第一次出现的 x |
| list.pop(index) | 删除指定位置的数据,默认为末尾数据 |
| list.clear() | 清空列表中元素 |
| list[index] = x | 修改指定位置的数据 |
| list1[start:end] = list2 | 修改列表切片的数据 |
| sorted(list,[reverse=True]) | 返回排序后的新列表,可选降序 |
| list.sort([reverse=True]) | 对列表就地排序,可选降序 |
| list.reverse() | 反转列表中的元素 |
| list.index(x,[start,[end]]) | 返回 x 在列表中首次出现的位置,可指定起始和结束范围 |
| list.count(x) | 返回 x 的数量 |
| len(list) | 返回列表元素个数 |
| max(list) | 返回列表中最大值 |
| min(list) | 返回列表中最小值 |
| sum(list) | 返回列表中所有元素和 |
| list.copy() | 拷贝列表 |
| list(x) | 将序列转换为列表 |
七、Dictionary(字典类型)
1、定义:
一个无序的键值对集合,键是唯一的,而值可以重复。
字典使用 {} 定义,键(key)和值(value)使用 : 连接,每个键值对之间使用 , 分隔。如{key1 : value1, key2 : value2}
字典没有索引。
字典可以通过键来获取对应的值。
值可以取任何数据类型,但键必须是不可变的,如字符串、数字、元组。
2、创建字典
# 可以通过{} 或 dict()创建字典
dict1 = {}
dict2 = dict()
dict3 = {"name": "Alice", "age": 18, "gender": "male"}
dict4 = dict(name="Bob", age=20, gender="female")
dict5 = dict([("name", "Tom"), ("age", 22), ("gender", "male")])
print(dict1)
print(dict2)
print(dict3)
print(dict4)
print(dict5)
# 也可以通过字典推导式创建字典
squares = {x: x**2 for x in range(4)}
print(squares) # {0: 0, 1: 1, 2: 4, 3: 9}
3、字典操作
# 访问字典
# 可通过 [] 访问字典中的元素。key不存在时会报错
dict1 = {"name": "Alice", "age": 18, "gender": "male"}
print(dict1["name"]) # Alice
print(dict1["age"]) # 18
print(dict1["gender"]) # male
print(dict1["address"]) # 报错
# 也可以通过get()获取字典中的元素。key不存在时会返回None,也可以指定默认值
dict1 = {"name": "Alice", "age": 18, "gender": "male"}
print(dict1.get("name")) # Alice
print(dict1.get("age")) # 18
print(dict1.get("gender")) # male
print(dict1.get("address")) # None
print(dict1.get("address", "earth")) # earth
# 向字典中添加元素
# 为字典指定的 key 赋值 value,若 key 原本不存在则会被添加
dict1 = {"name": "Alice", "age": 18, "gender": "male"}
dict1["address"] = "earth"
print(dict1)
# 修改字典中元素
# 通过 key 修改对应的 value
dict1 = {"name": "Alice", "age": 18, "gender": "male"}
dict1["name"] = "Bob"
print(dict1)
# 检查成员是否为字典中的 key
dict1 = {"name": "Alice", "age": 81, "gender": "male"}
print("name" in dict1) # 检查key是否存在
print("Alice" in dict1) # 无法直接检查value是否存在
# 获取字典长度
dict1 = {"name": "Alice", "age": 81, "gender": "male"}
print(len(dict1)) # 3
-------------------- 遍历 -------------------------------
# 遍历字典
my_dict = {'Name': 'Tom', 'Age': 17}
# 遍历出所有k
keys = my_dict.keys()
for k in keys:
print (k)
print("-" *20)
# 遍历出所有v
vals = my_dict.values()
print(vals)
for v in vals:
print (v)
print("-" *20)
# k-v遍历
keys = my_dict.keys()
for k in keys:
print (k + "---" + str(my_dict[k]))
print("-" *20)
kv = my_dict.items()
for i in kv:
print(i)
----------------------------------------------------------------
-------------------- 删除字典元素 -------------------------------
my_dict = {'Name': 'Tom', 'Age': 17}
del my_dict['Name'] # 删除键 'Name'
# my_dict.clear() # 清空字典
# del my_dict # 删除字典
print (my_dict)
4、常用函数
| 函数 | 说明 |
|---|---|
| del dict[key] | 根据 key 删除键值对 |
| dict.pop(key[,default]) | 获取 key 所对应的 value,同时删除该键值对,可设置默认值 |
| dict.popitem() | 取出字典中的最后插入的键值对,字典为空则报错 |
| dict.clear() | 清空字典 |
| dict1.update(dict2) | 将 dict2 中的键值对更新到 dict1 中 |
| dict.get(key[,default]) | 获取字典中 key 对应 value,可设置默认值 |
| dict.setdefault(key[,default]) | 获取字典中 key 对应 value,可设置默认值。若 key 不存在于字典中,将会添加 key 并将 value 设为默认值 |
| dict.keys() | 获取字典所有的 key,返回一个视图对象。字典改变,视图也会跟着变化 |
| dict.values() | 获取字典所有的 value,返回一个视图对象 |
| dict.items() | 获取字典所有的 (key,value),返回一个视图对象 |
| dict.copy() | 拷贝字典 |
| dict.fromkeys(seq[,default]) | 以序列 seq 中元素做字典的 key 创建一个新字典,可设置 value 的默认值 |
八、Set(集合类型)
1、定义:
集合是无序的,且不包含重复元素。
集合使用 {} 定义,数据之间使用 , 分隔,也可以使用set()定义。
集合没有索引,所以不能通过切片方式访问集合元素。
集合中元素可以是不同的类型。
集合可以进行数学上的集合操作,如并集、交集和差集。
集合适用于需要快速成员检查、消除重复项和集合运算的场景。
2、创建集合
# 可以通过{}或set()创建集合,但创建空集合需要使用set()而非{},因为{}会创建空字典
set1 = {1, 2, 3}
set2 = set([1, 2, 3]) # 使用set()函数从列表创建集合
set3 = set()
print(set1, set2, set3)
# 也可以通过集合推导式创建集合
set1 = {x for x in range(10) if x % 2 == 0}
print(set1) # {0, 2, 4, 6, 8}
3、集合操作
# 向集合中添加元素
set1 = {1, 2, 3}
set1.add(4)
set1.add(5)
print(set1)
# 从集合中删除元素
set1 = {1, 2, 3}
set1.remove(2)
print(set1)
# 检查成员是否为集合中元素
set1 = {1, 2, 3, 4, 5}
print(2 in set1) # True
# 获取集合长度
set1 = {1, 2, 3, 4, 5}
print(len(set1)) # 5
# 求集合中元素的最大值、最小值、加和
set1 = {1, 2, 3, 4, 5}
print(max(set1)) # 5
print(min(set1)) # 1
print(sum(set1)) # 15
# 遍历集合
my_set = {1, 2, 3, 4, 5}
for item in my_set:
print(item)
4、常用函数
| 函数 | 说明 |
|---|---|
| set.add(x) | 添加元素 |
| set.update(x) | 添加元素,x 可以为列表、元组、字符串、字典等可迭代对象 |
| set.union(x) | 添加元素后返回一个新的集合,x 可以为列表、元组、字符串、字典等可迭代对象 |
| set.remove(x) | 从集合中移除 x,x 不存在则报错 |
| set.discard(x) | 从集合中移除 x,x 不存在也不报错 |
| set.pop() | 随机取出集合中的一个元素,如果集合为空则报错 |
| set.clear() | 清空集合 |
| set.difference(x1,...) | 求 set1 和 x1 的差集,返回一个新的集合 |
| set.difference_update(x1,...) | 求 set1 和 x1 的差集 |
| set.intersection(x1,...) | 求 set1 和 x1 的交集,返回一个新的集合 |
| set.intersection_update(x1,...) | 求 set1 和 x1 的交集 |
| set1 & set2 | 两集合求交集 |
| set1 | set2 |
| set1 - set2 | 两集合求差集 |
| set1.isdisjoint(set2) | 判断两集合是否没有交集 |
| set1.issubset(set2) | 判断 set1 是否为 set2 的子集 |
| set1.issuperset(set2) | 判断 set2 是否为 set1 的子集(即 set1 是否为 set2 的超集) |
| set1.symmetric_difference(set2) | 求两集合中不重复的元素,返回一个新的集合 |
| set1.symmetric_difference_update(set2) | 求两集合中不重复的元素 |
| set.copy() | 拷贝集合 |
| len(set) | 返回集合元素个数 |
| max(set) | 求集合中元素的最大值 |
| min(set) | 求集合中元素的最小值 |
| sum(set) | 求集合中元素的加和 |
九、数据类型转换函数
Python 提供了多种内置函数用于数据类型转换:
1、转换为数字
print(int("123")) # 123
print(float("3.14")) # 3.14
print(bool(0)) # False
print(bool("")) # False
print(bool([])) # False
print(bool(None)) # False
2、转换为字符串
print(str(100)) # "100"
print(str(3.14)) # "3.14"
print(str(True)) # "True"
3、转换为序列类型
print(list("abc")) # ['a', 'b', 'c']
print(tuple([1, 2])) # (1, 2)
print(set([1, 2, 2])) # {1, 2}
4、转换为字典
# 从键值对序列创建字典
pairs = [('a', 1), ('b', 2)]
print(dict(pairs)) # {'a': 1, 'b': 2}
# 使用 zip 创建字典
keys = ['name', 'age']
values = ['Alice', 25]
print(dict(zip(keys, values))) # {'name': 'Alice', 'age': 25}
5、类型判断函数
print(type(10)) # <class 'int'>
print(isinstance(10, int)) # True
print(isinstance([1, 2], (list, tuple))) # True(检查多种类型)
十、类型转换实战示例
# 用户输入处理
user_input = input("请输入您的年龄和身高(用逗号分隔): ")
age_str, height_str = user_input.split(',')
age = int(age_str.strip())
height = float(height_str.strip())
print(f"年龄: {age}岁,身高: {height}cm")
# 数据清洗与转换
data = ["1", "2", "three", "4", "5.5", ""]
cleaned_data = []
for item in data:
if item.isdigit():
cleaned_data.append(int(item))
else:
try:
cleaned_data.append(float(item))
except ValueError:
cleaned_data.append(0) # 无法转换的设为0
print(cleaned_data) # [1, 2, 0, 4, 5.5, 0]
十一、列表、元组、字典和集合的区别
总结
- 1、六大数据类型:数字、字符串、元组、列表、字典、集合是 Python 最常用的数据类型
- 2、不可变类型:数字、字符串、元组(创建后不能修改)
- 3、可变类型:列表、字典、集合(可以修改内容)
- 4、类型转换:使用 int()、float()、str()、list()、tuple()、set()、dict() 等函数灵活转换类型
- 5、选择依据:根据数据是否需要修改、是否需要有序、是否需要键值对等特性选择合适的类型
- 6、掌握这些数据类型及其转换方法,是 Python 编程的基础,也是编写高效、清晰代码的关键。

浙公网安备 33010602011771号