Python基本数据类型详解
Python是一种动态类型语言,变量不需要声明类型。本文将详细介绍Python的基本数据类型,包括数字、字符串、布尔值、None以及各种容器类型(列表、元组、集合、字典)。
一、数据类型概述
Python的基本数据类型可以分为以下几类:
- 数字类型:整数、浮点数、复数
- 序列类型:字符串、列表、元组
- 集合类型:集合
- 映射类型:字典
- 特殊类型:布尔值、None
可以使用type()函数查看一个变量的数据类型:
x = 10
print(type(x)) # <class 'int'>
name = "Python"
print(type(name)) # <class 'str'>
二、数字类型
Python支持三种数字类型:整数(int)、浮点数(float)和复数(complex)。
1. 整数(int)
整数是没有小数部分的数字,可以是正数、负数或零。
特点
- Python 3中的整数可以是任意大小,不受内存限制
- 支持十进制、二进制、八进制和十六进制表示
创建方法
# 十进制整数
num1 = 10
num2 = -5
num3 = 0
# 二进制表示(以0b或0B开头)
binary = 0b1010 # 十进制的10
# 八进制表示(以0o或0O开头)
octal = 0o12 # 十进制的10
# 十六进制表示(以0x或0X开头)
hexadecimal = 0xA # 十进制的10
常用操作
# 算术运算
print(10 + 3) # 13
print(10 - 3) # 7
print(10 * 3) # 30
print(10 / 3) # 3.3333333333333335
print(10 // 3) # 3(整数除法)
print(10 % 3) # 1(取余)
print(10 ** 3) # 1000(幂运算)
# 比较运算
print(10 > 3) # True
print(10 < 3) # False
print(10 == 3) # False
# 类型转换
print(int(3.14)) # 3
print(int("10")) # 10
2. 浮点数(float)
浮点数是带有小数部分的数字。
特点
- 浮点数是近似值,可能存在精度问题
- 使用科学计数法表示时,用e或E表示10的幂
创建方法
# 普通浮点数
float1 = 3.14
float2 = -0.5
float3 = 2.0
# 科学计数法
float4 = 1.23e3 # 1.23 * 10^3 = 1230.0
float5 = 1.23e-3 # 1.23 * 10^-3 = 0.00123
常用操作
# 算术运算
print(3.14 + 2.71) # 5.85
print(3.14 - 2.71) # 0.43000000000000015(注意精度问题)
print(3.14 * 2) # 6.28
print(3.14 / 2) # 1.57
# 比较运算
print(3.14 > 2.71) # True
# 类型转换
print(float(10)) # 10.0
print(float("3.14")) # 3.14
3. 复数(complex)
复数由实部和虚部组成,虚部用j或J表示。
特点
- 实部和虚部都是浮点数
- 支持复数的各种数学运算
创建方法
# 直接创建
complex1 = 1 + 2j
complex2 = -3j
complex3 = 2.5 + 1.5j
# 使用complex()函数创建
complex4 = complex(1, 2) # 1+2j
complex5 = complex(3) # 3+0j
常用操作
# 访问实部和虚部
c = 1 + 2j
print(c.real) # 1.0
print(c.imag) # 2.0
# 复数共轭
print(c.conjugate()) # (1-2j)
# 算术运算
c1 = 1 + 2j
c2 = 3 + 4j
print(c1 + c2) # (4+6j)
print(c1 - c2) # (-2-2j)
print(c1 * c2) # (-5+10j)
print(c1 / c2) # (0.44+0.08j)
三、字符串类型(str)
字符串是由字符组成的不可变序列,用于表示文本数据。
特点
- 不可变:创建后不能修改内容
- 支持索引和切片操作
- 可以包含任意Unicode字符
创建方法
字符串可以使用单引号'、双引号"或三引号'''/"""创建:
# 单引号字符串
str1 = 'Hello, World!'
# 双引号字符串
str2 = "Hello, World!"
# 三引号字符串(支持多行)
str3 = '''Hello,
World!''' # 包含换行符
# 三引号字符串也可以使用双引号
str4 = """Hello,
World!"""
转义字符
当需要在字符串中包含特殊字符时,可以使用转义字符\:
# 转义字符示例
print('He said, "Hello!"') # He said, "Hello!"
print('Line 1\nLine 2') # 换行
print('\tTabbed text') # 制表符
print('C:\\Users\\Name') # 反斜杠
print('\x41') # 十六进制转义,输出A
字符串操作
1. 字符串拼接和重复
# 字符串拼接
str1 = "Hello, "
str2 = "World!"
str3 = str1 + str2
print(str3) # Hello, World!
# 字符串重复
str4 = "*" * 10
print(str4) # **********
2. 字符串索引和切片
text = "Python"
# 索引(从0开始)
print(text[0]) # P
print(text[1]) # y
print(text[-1]) # n(从末尾开始计数)
# 切片 [start:end:step]
print(text[0:3]) # Pyt(从索引0到3,不包含3)
print(text[:3]) # Pyt(从开头到索引3)
print(text[3:]) # hon(从索引3到末尾)
print(text[::2]) # Pto(步长为2)
print(text[::-1]) # nohtyP(反转字符串)
3. 字符串长度
text = "Hello, World!"
print(len(text)) # 13
4. 字符串方法
字符串提供了丰富的内置方法:
text = "Hello, World!"
# 大小写转换
print(text.upper()) # HELLO, WORLD!
print(text.lower()) # hello, world!
print(text.title()) # Hello, World!
print(text.capitalize()) # Hello, world!
print(text.swapcase()) # hELLO, wORLD!
# 字符串查找
print(text.find("World")) # 7
print(text.find("Python")) # -1(未找到)
print(text.index("World")) # 7
# print(text.index("Python")) # 抛出ValueError
# 字符串替换
print(text.replace("World", "Python")) # Hello, Python!
# 字符串分割
print(text.split(", ")) # ['Hello', 'World!']
# 字符串连接
words = ['Hello', 'World!']
print(", ".join(words)) # Hello, World!
# 字符串判断
print(text.startswith("Hello")) # True
print(text.endswith("!")) # True
print(text.isalpha()) # False(包含非字母字符)
print("123".isdigit()) # True
print("abc123".isalnum()) # True
print(" ".isspace()) # True
# 字符串格式化
name = "张荣殿"
age = 30
print(f"我的名字是{name},今年{age}岁。") # 我的名字是张荣殿,今年30岁。
print("我的名字是{},今年{}岁。".format(name, age)) # 我的名字是张荣殿,今年30岁。
print("我的名字是%s,今年%d岁。" % (name, age)) # 我的名字是张荣殿,今年30岁。
四、布尔类型(bool)
布尔类型表示真(True)或假(False),用于逻辑判断。
特点
- 布尔类型只有两个值:True和False
- 布尔值可以转换为整数:True == 1,False == 0
创建方法
# 直接赋值
t = True
f = False
# 逻辑运算结果
result1 = 10 > 5 # True
result2 = 10 == 5 # False
# 布尔转换
print(bool(1)) # True
print(bool(0)) # False
print(bool("Hello")) # True
print(bool("")) # False
print(bool([])) # False
print(bool({})) # False
print(bool(None)) # False
布尔运算
| 运算符 | 描述 | 示例 |
|---|---|---|
and |
逻辑与(都为真才为真) | True and False → False |
or |
逻辑或(有一个为真就为真) | True or False → True |
not |
逻辑非(取反) | not True → False |
# 布尔运算示例
x = True
y = False
print(x and y) # False
print(x or y) # True
print(not x) # False
五、None类型
None是Python中的一个特殊值,表示空值或不存在的值。
特点
- None是一个单独的类型:NoneType
- 与其他值比较时都为False(除了None本身)
- 常用于函数的默认参数或返回值
创建方法
# 直接赋值
n = None
# 函数返回值(无返回值时默认返回None)
def no_return():
pass
result = no_return()
print(result) # None
常用操作
# None的比较
x = None
print(x is None) # True(使用is判断)
print(x == None) # True(也可以使用==,但推荐使用is)
# None转换为其他类型
print(bool(None)) # False
print(int(None)) # TypeError
print(str(None)) # "None"
六、列表类型(list)
列表是有序、可变的序列,可以存储不同类型的元素。
特点
- 有序:元素有固定的顺序
- 可变:可以添加、删除、修改元素
- 可嵌套:列表中可以包含其他列表
- 可以存储不同类型的元素
创建方法
# 使用方括号创建
list1 = [1, 2, 3, 4, 5]
list2 = ["apple", "banana", "orange"]
list3 = [1, "apple", True, 3.14] # 混合类型
list4 = [] # 空列表
# 使用list()函数创建
list5 = list() # 空列表
list6 = list("Python") # ['P', 'y', 't', 'h', 'o', 'n']
list7 = list(range(5)) # [0, 1, 2, 3, 4]
列表操作
1. 索引和切片
fruits = ["apple", "banana", "orange", "grape"]
# 索引
print(fruits[0]) # apple
print(fruits[-1]) # grape
# 切片
print(fruits[0:2]) # ['apple', 'banana']
print(fruits[2:]) # ['orange', 'grape']
print(fruits[::2]) # ['apple', 'orange']
2. 列表长度
fruits = ["apple", "banana", "orange"]
print(len(fruits)) # 3
3. 添加元素
fruits = ["apple", "banana"]
# append():在末尾添加一个元素
fruits.append("orange") # ['apple', 'banana', 'orange']
# extend():添加另一个可迭代对象的所有元素
fruits.extend(["grape", "watermelon"])
# ['apple', 'banana', 'orange', 'grape', 'watermelon']
# insert():在指定位置插入元素
fruits.insert(1, "pear") # ['apple', 'pear', 'banana', 'orange', 'grape', 'watermelon']
4. 删除元素
fruits = ["apple", "banana", "orange", "grape"]
# pop():删除并返回指定位置的元素(默认最后一个)
removed = fruits.pop() # 删除grape,返回'grape'
print(fruits) # ['apple', 'banana', 'orange']
removed = fruits.pop(1) # 删除banana,返回'banana'
print(fruits) # ['apple', 'orange']
# remove():删除第一个匹配的元素
fruits = ["apple", "banana", "orange", "banana"]
fruits.remove("banana")
print(fruits) # ['apple', 'orange', 'banana']
# del:删除指定位置的元素或整个列表
del fruits[0] # 删除第一个元素
del fruits # 删除整个列表
5. 修改元素
fruits = ["apple", "banana", "orange"]
fruits[1] = "pear" # 修改第二个元素
print(fruits) # ['apple', 'pear', 'orange']
6. 列表方法
fruits = ["apple", "banana", "orange", "apple"]
# count():统计元素出现的次数
print(fruits.count("apple")) # 2
# index():返回元素第一次出现的索引
print(fruits.index("banana")) # 1
# sort():排序
numbers = [3, 1, 4, 1, 5, 9]
numbers.sort()
print(numbers) # [1, 1, 3, 4, 5, 9]
# reverse():反转列表
fruits.reverse()
print(fruits) # ['apple', 'orange', 'banana', 'apple']
# copy():复制列表
fruits_copy = fruits.copy()
7. 列表推导式
列表推导式是一种简洁创建列表的方法:
# 基本语法:[表达式 for 变量 in 可迭代对象 if 条件]
# 创建1-10的平方列表
squares = [x**2 for x in range(1, 11)]
print(squares) # [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
# 过滤偶数
even_numbers = [x for x in range(1, 11) if x % 2 == 0]
print(even_numbers) # [2, 4, 6, 8, 10]
# 嵌套列表推导式
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flattened = [num for row in matrix for num in row]
print(flattened) # [1, 2, 3, 4, 5, 6, 7, 8, 9]
七、元组类型(tuple)
元组是有序、不可变的序列,与列表类似但不能修改。
特点
- 不可变:创建后不能添加、删除或修改元素
- 可以存储不同类型的元素
- 可以嵌套
- 比列表更节省内存
创建方法
# 使用圆括号创建
t1 = (1, 2, 3, 4, 5)
t2 = ("apple", "banana", "orange")
t3 = (1, "apple", True) # 混合类型
# 单个元素的元组需要加逗号
t4 = (5,)
print(type(t4)) # <class 'tuple'>
# 省略圆括号
=t5 = 1, 2, 3
print(type(t5)) # <class 'tuple'>
# 使用tuple()函数创建
t6 = tuple() # 空元组
t7 = tuple([1, 2, 3]) # (1, 2, 3)
t8 = tuple("Python") # ('P', 'y', 't', 'h', 'o', 'n')
元组操作
1. 索引和切片
元组的索引和切片与列表相同:
t = (1, 2, 3, 4, 5)
print(t[0]) # 1
print(t[-1]) # 5
print(t[1:3]) # (2, 3)
print(t[::2]) # (1, 3, 5)
2. 元组长度
t = (1, 2, 3, 4, 5)
print(len(t)) # 5
3. 元组方法
由于元组不可变,元组的方法很少:
t = (1, 2, 3, 2, 4)
# count():统计元素出现的次数
print(t.count(2)) # 2
# index():返回元素第一次出现的索引
print(t.index(3)) # 2
4. 元组解包
元组解包是将元组的元素赋值给多个变量:
# 基本解包
coordinates = (10, 20, 30)
x, y, z = coordinates
print(x) # 10
print(y) # 20
print(z) # 30
# 扩展解包(Python 3+)
t = (1, 2, 3, 4, 5)
first, *middle, last = t
print(first) # 1
print(middle) # [2, 3, 4]
print(last) # 5
# 交换变量
a, b = 1, 2
a, b = b, a
print(a, b) # 2 1
八、集合类型(set)
集合是无序、不重复的元素集合。
特点
- 无序:元素没有固定的顺序
- 不重复:自动去重
- 支持集合运算(并集、交集、差集等)
创建方法
# 使用花括号创建
s1 = {1, 2, 3, 4, 5}
s2 = {"apple", "banana", "orange"}
# 注意:空集合不能使用{}创建,{}创建的是空字典
empty_set = set()
# 使用set()函数创建
set_from_list = set([1, 2, 2, 3, 4, 4]) # {1, 2, 3, 4}(去重)
set_from_str = set("Python") # {'P', 'y', 't', 'h', 'o', 'n'}
集合操作
1. 添加元素
s = {1, 2, 3}
# add():添加单个元素
s.add(4) # {1, 2, 3, 4}
# update():添加另一个可迭代对象的所有元素
s.update([4, 5, 6]) # {1, 2, 3, 4, 5, 6}(自动去重)
2. 删除元素
s = {1, 2, 3, 4, 5}
# remove():删除指定元素,如果不存在会引发KeyError
s.remove(3) # {1, 2, 4, 5}
# discard():删除指定元素,如果不存在不会引发错误
s.discard(6) # {1, 2, 4, 5}(6不存在,但不会出错)
# pop():删除并返回一个随机元素
removed = s.pop() # 删除并返回1(或其他随机元素)
# clear():清空集合
s.clear() # set()
3. 集合运算
| 操作 | 描述 | 运算符 | 方法 |
|---|---|---|---|
| 并集 | 所有元素 | ` | ` |
| 交集 | 共同元素 | & |
intersection() |
| 差集 | 属于第一个集合但不属于第二个集合 | - |
difference() |
| 对称差集 | 只属于一个集合的元素 | ^ |
symmetric_difference() |
s1 = {1, 2, 3, 4}
s2 = {3, 4, 5, 6}
# 并集
print(s1 | s2) # {1, 2, 3, 4, 5, 6}
print(s1.union(s2)) # {1, 2, 3, 4, 5, 6}
# 交集
print(s1 & s2) # {3, 4}
print(s1.intersection(s2)) # {3, 4}
# 差集
print(s1 - s2) # {1, 2}
print(s1.difference(s2)) # {1, 2}
# 对称差集
print(s1 ^ s2) # {1, 2, 5, 6}
print(s1.symmetric_difference(s2)) # {1, 2, 5, 6}
4. 集合推导式
# 基本语法:{表达式 for 变量 in 可迭代对象 if 条件}
# 创建1-10的平方集合
squares = {x**2 for x in range(1, 11)}
print(squares) # {64, 1, 4, 36, 100, 9, 16, 49, 81, 25}
# 去重
numbers = [1, 2, 2, 3, 4, 4, 5]
distinct = {x for x in numbers}
print(distinct) # {1, 2, 3, 4, 5}
九、字典类型(dict)
字典是无序的键值对集合,键必须是唯一且不可变的。
特点
- 无序(Python 3.7+后保证插入顺序)
- 键必须是不可变类型(如字符串、数字、元组)
- 值可以是任意类型
- 查找速度快(时间复杂度为O(1))
创建方法
# 使用花括号创建
dict1 = {
"name": "张荣殿",
"age": 30,
"city": "北京"
}
# 创建空字典
dict2 = {}
# 使用dict()函数创建
dict3 = dict() # 空字典
dict4 = dict(name="张荣殿", age=30, city="北京")
dict5 = dict([("name", "张荣殿"), ("age", 30)])
# 使用字典推导式创建
dict6 = {x: x**2 for x in range(1, 6)} # {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
字典操作
1. 访问元素
person = {"name": "张荣殿", "age": 30, "city": "北京"}
# 使用键访问值
print(person["name"]) # 张荣殿
# 使用get()方法访问值(更安全)
print(person.get("age")) # 30
print(person.get("gender", "未知")) # 未知(键不存在时返回默认值)
2. 添加和修改元素
person = {"name": "张荣殿", "age": 30}
# 添加新键值对
person["city"] = "北京" # {'name': '张荣殿', 'age': 30, 'city': '北京'}
# 修改已有键的值
person["age"] = 31 # {'name': '张荣殿', 'age': 31, 'city': '北京'}
# 使用update()方法批量更新
person.update({"gender": "男", "hobby": "编程"})
# {'name': '张荣殿', 'age': 31, 'city': '北京', 'gender': '男', 'hobby': '编程'}
3. 删除元素
person = {"name": "张荣殿", "age": 30, "city": "北京", "gender": "男"}
# del:删除指定键值对
del person["gender"] # {'name': '张荣殿', 'age': 30, 'city': '北京'}
# pop():删除并返回指定键的值
city = person.pop("city") # 返回"北京",字典变为{'name': '张荣殿', 'age': 30}
# popitem():删除并返回最后一个键值对
person.update({"city": "北京", "hobby": "编程"})
last_item = person.popitem() # 返回("hobby", "编程")
# clear():清空字典
person.clear() # {}
4. 字典方法
person = {"name": "张荣殿", "age": 30, "city": "北京"}
# keys():获取所有键
print(person.keys()) # dict_keys(['name', 'age', 'city'])
# values():获取所有值
print(person.values()) # dict_values(['张荣殿', 30, '北京'])
# items():获取所有键值对
print(person.items()) # dict_items([('name', '张荣殿'), ('age', 30), ('city', '北京')])
# 遍历字典
for key in person:
print(key, person[key])
for key, value in person.items():
print(key, value)
# 复制字典
person_copy = person.copy()
5. 字典推导式
# 基本语法:{键表达式: 值表达式 for 变量 in 可迭代对象 if 条件}
# 创建1-5的平方字典
squares = {x: x**2 for x in range(1, 6)}
print(squares) # {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
# 过滤偶数键
even_dict = {x: x*2 for x in range(1, 11) if x % 2 == 0}
print(even_dict) # {2: 4, 4: 8, 6: 12, 8: 16, 10: 20}
# 从两个列表创建字典
keys = ["name", "age", "city"]
values = ["张荣殿", 30, "北京"]
dict_from_lists = {keys[i]: values[i] for i in range(len(keys))}
print(dict_from_lists) # {'name': '张荣殿', 'age': 30, 'city': '北京'}
十、数据类型转换
Python提供了各种类型转换函数,可以在不同数据类型之间进行转换:
| 函数 | 描述 | 示例 |
|---|---|---|
int() |
转换为整数 | int(3.14) → 3 |
float() |
转换为浮点数 | float(10) → 10.0 |
complex() |
转换为复数 | complex(1, 2) → 1+2j |
str() |
转换为字符串 | str(10) → "10" |
bool() |
转换为布尔值 | bool(0) → False |
list() |
转换为列表 | list((1, 2, 3)) → [1, 2, 3] |
tuple() |
转换为元组 | tuple([1, 2, 3]) → (1, 2, 3) |
set() |
转换为集合 | set([1, 2, 2, 3]) → {1, 2, 3} |
dict() |
转换为字典 | dict([("a", 1), ("b", 2)]) → {"a": 1, "b": 2} |
# 类型转换示例
x = "123"
print(type(x)) # <class 'str'>
# 转换为整数
y = int(x)
print(y, type(y)) # 123 <class 'int'>
# 转换为浮点数
z = float(y)
print(z, type(z)) # 123.0 <class 'float'>
# 转换为字符串
w = str(z)
print(w, type(w)) # 123.0 <class 'str'>
# 列表转换为元组
lst = [1, 2, 3]
tpl = tuple(lst)
print(tpl, type(tpl)) # (1, 2, 3) <class 'tuple'>
总结
Python提供了丰富的数据类型,每种类型都有其特定的用途和特点:
- 数字类型:用于数值计算
- 字符串类型:用于文本处理
- 布尔类型:用于逻辑判断
- None类型:表示空值
- 列表:有序可变的元素集合
- 元组:有序不可变的元素集合
- 集合:无序不重复的元素集合
- 字典:键值对的集合,用于快速查找
了解并掌握这些基本数据类型是学习Python的基础,它们为更复杂的编程任务提供了坚实的基础。
发布网站:荣殿教程(zhangrongdian.com)
作者:张荣殿