0
点赞
收藏
分享

微信扫一扫

Python3 基本数据类型完全指南:从入门到实践

Python3 是一种动态类型语言,变量在运行时会自动确定数据类型。本文将系统介绍 Python3 中的所有基本数据类型,包括它们的特性、操作方法和实际应用场景,并提供丰富的代码示例。

一、数值类型(Numeric Types)

Python3 支持三种主要的数值类型:整数、浮点数和复数。

1. 整数(int)

Python3 的整数没有大小限制,可以表示任意大小的整数:

python# 整数示例
 a = 10          # 十进制
 b = 0b1010      # 二进制 (等于10)
 c = 0o12        # 八进制 (等于10)
 d = 0xA         # 十六进制 (等于10)
  
 print(a, b, c, d)  # 输出: 10 10 10 10
 print(type(a))     # 输出: <class 'int'>
  
 # 大整数支持
 big_num = 123456789012345678901234567890
 print(big_num)     # 不会溢出

2. 浮点数(float)

浮点数用于表示带有小数部分的数字:

python# 浮点数示例
 x = 3.14
 y = 2.8e2       # 科学计数法,等于280.0
 z = -0.0001
  
 print(x, y, z)  # 输出: 3.14 280.0 -0.0001
 print(type(y))  # 输出: <class 'float'>
  
 # 浮点数精度问题
 print(0.1 + 0.2 == 0.3)  # 输出: False (由于浮点数精度问题)
 print(round(0.1 + 0.2, 1) == 0.3)  # 输出: True (使用round解决)

3. 复数(complex)

复数由实部和虚部组成,虚部用 j 或 J 表示:

python# 复数示例
 c1 = 3 + 4j
 c2 = complex(2, -5)  # 等价于 2 - 5j
  
 print(c1, c2)         # 输出: (3+4j) (2-5j)
 print(type(c1))        # 输出: <class 'complex'>
  
 # 复数运算
 print(c1 + c2)         # 输出: (5-1j)
 print(c1.real, c1.imag) # 输出: 3.0 4.0 (实部和虚部)

4. 数值运算

python# 基本运算
 a, b = 10, 3
 print(a + b)  # 加法: 13
 print(a - b)  # 减法: 7
 print(a * b)  # 乘法: 30
 print(a / b)  # 除法: 3.333... (结果总是float)
 print(a // b) # 整除: 3 (向下取整)
 print(a % b)  # 取模: 1 (余数)
 print(a ** b) # 幂运算: 1000
  
 # 增强赋值运算符
 x = 5
 x += 3  # 等价于 x = x + 3
 print(x)  # 输出: 8
  
 # 比较运算
 print(5 > 3)   # True
 print(5 == 5)  # True
 print(5 != 3)  # True

二、序列类型(Sequence Types)

序列是Python中最基本的数据结构,包括字符串、列表和元组。

1. 字符串(str)

字符串是不可变的字符序列,用单引号、双引号或三引号定义:

python# 字符串定义
 s1 = 'Hello'
 s2 = "World"
 s3 = """This is a
 multi-line string"""
  
 print(s1, s2, s3)
 print(type(s1))  # <class 'str'>
  
 # 字符串操作
 print(s1 + " " + s2)  # 拼接: Hello World
 print(s1 * 3)         # 重复: HelloHelloHello
 print(len(s1))        # 长度: 5
 print('H' in s1)      # 成员检查: True
  
 # 字符串索引和切片
 greeting = "Python is awesome"
 print(greeting[0])     # 第一个字符: P
 print(greeting[-1])    # 最后一个字符: e
 print(greeting[7:9])   # 切片: is
 print(greeting[:6])    # 从开始到索引6: Python 
 print(greeting[7:])    # 从索引7到结束: is awesome
  
 # 字符串方法
 text = "  python programming  "
 print(text.upper())      # 转为大写: PYTHON PROGRAMMING
 print(text.lower())      # 转为小写:  python programming
 print(text.strip())      # 去除首尾空格: python programming
 print(text.split())      # 分割为列表: ['python', 'programming']
 print(" ".join(["Hello", "World"]))  # 连接列表: Hello World
 print("py" in text)      # 检查子串: True
 print(text.find("pro"))  # 查找子串位置: 7
 print(text.replace("python", "java"))  # 替换:   java programming

2. 列表(list)

列表是可变的有序序列,可以包含不同类型的元素:

python# 列表定义
 fruits = ['apple', 'banana', 'orange']
 mixed = [1, "hello", 3.14, True]
 empty_list = []
  
 print(fruits, mixed)
 print(type(fruits))  # <class 'list'>
  
 # 列表操作
 print(len(fruits))  # 长度: 3
 print('apple' in fruits)  # 成员检查: True
  
 # 列表索引和切片
 print(fruits[0])     # 第一个元素: apple
 print(fruits[-1])    # 最后一个元素: orange
 print(fruits[1:3])   # 切片: ['banana', 'orange']
  
 # 列表方法
 numbers = [1, 3, 5, 2, 4]
 numbers.append(6)     # 添加元素到末尾
 print(numbers)        # [1, 3, 5, 2, 4, 6]
  
 numbers.insert(0, 0)  # 在指定位置插入
 print(numbers)        # [0, 1, 3, 5, 2, 4, 6]
  
 removed = numbers.pop(2)  # 移除并返回指定位置元素
 print(removed, numbers)    # 3 [0, 1, 5, 2, 4, 6]
  
 numbers.remove(5)     # 移除第一个匹配的元素
 print(numbers)        # [0, 1, 2, 4, 6]
  
 numbers.sort()        # 排序
 print(numbers)        # [0, 1, 2, 4, 6]
  
 numbers.reverse()     # 反转
 print(numbers)        # [6, 4, 2, 1, 0]
  
 # 列表推导式
 squares = [x**2 for x in range(5)]
 print(squares)        # [0, 1, 4, 9, 16]

3. 元组(tuple)

元组是不可变的有序序列,定义后不能修改:

python# 元组定义
 colors = ('red', 'green', 'blue')
 single_element = (42,)  # 单元素元组需要逗号
 empty_tuple = ()
  
 print(colors, single_element)
 print(type(colors))  # <class 'tuple'>
  
 # 元组操作
 print(len(colors))   # 长度: 3
 print(colors[1])     # 索引: green
 print(colors[::-1])  # 反转: ('blue', 'green', 'red')
  
 # 元组解包
 x, y, z = colors
 print(x, y, z)       # red green blue
  
 # 元组与列表转换
 tuple_from_list = tuple([1, 2, 3])
 list_from_tuple = list(('a', 'b', 'c'))
 print(tuple_from_list, list_from_tuple)  # (1, 2, 3) ['a', 'b', 'c']
  
 # 元组方法
 print(colors.count('red'))  # 计数: 1
 print(colors.index('blue')) # 索引: 2

三、映射类型(Mapping Type)

字典(dict)

字典是可变的键值对集合,键必须是不可变类型:

python# 字典定义
 person = {
     'name': 'Alice',
     'age': 25,
     'city': 'New York'
 }
 empty_dict = {}
  
 print(person, empty_dict)
 print(type(person))  # <class 'dict'>
  
 # 字典访问
 print(person['name'])  # Alice
 print(person.get('age'))  # 25
 print(person.get('country', 'Unknown'))  # 默认值: Unknown
  
 # 字典操作
 person['job'] = 'Engineer'  # 添加键值对
 person['age'] = 26          # 修改值
 print(person)  # {'name': 'Alice', 'age': 26, 'city': 'New York', 'job': 'Engineer'}
  
 # 删除键值对
 del person['city']
 removed_value = person.pop('job')
 print(removed_value, person)  # Engineer {'name': 'Alice', 'age': 26}
  
 # 字典方法
 keys = person.keys()    # 所有键
 values = person.values() # 所有值
 items = person.items()   # 所有键值对
 print(keys, values, items)  # dict_keys(['name', 'age']) dict_values(['Alice', 26]) dict_items([('name', 'Alice'), ('age', 26)])
  
 # 字典推导式
 squares_dict = {x: x**2 for x in range(5)}
 print(squares_dict)  # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
  
 # 字典合并 (Python 3.9+)
 dict1 = {'a': 1, 'b': 2}
 dict2 = {'b': 3, 'c': 4}
 merged_dict = dict1 | dict2
 print(merged_dict)  # {'a': 1, 'b': 3, 'c': 4}

四、集合类型(Set Type)

集合是无序的不重复元素集合,分为可变集合(set)和不可变集合(frozenset)。

1. 可变集合(set)

python# 集合定义
 numbers_set = {1, 2, 3, 2, 1}  # 自动去重
 from_list = set([3, 1, 4, 1, 5])
 empty_set = set()  # 注意: {} 是空字典,不是空集合
  
 print(numbers_set, from_list)  # {1, 2, 3} {1, 3, 4, 5}
 print(type(numbers_set))  # <class 'set'>
  
 # 集合操作
 print(len(numbers_set))  # 长度: 3
 print(2 in numbers_set)  # 成员检查: True
  
 # 添加和删除元素
 numbers_set.add(4)
 numbers_set.discard(2)  # 安全删除,不存在也不会报错
 print(numbers_set)  # {1, 3, 4}
  
 # 集合运算
 a = {1, 2, 3, 4}
 b = {3, 4, 5, 6}
 print(a | b)  # 并集: {1, 2, 3, 4, 5, 6}
 print(a & b)  # 交集: {3, 4}
 print(a - b)  # 差集: {1, 2}
 print(a ^ b)  # 对称差集: {1, 2, 5, 6}
  
 # 集合推导式
 even_set = {x for x in range(10) if x % 2 == 0}
 print(even_set)  # {0, 2, 4, 6, 8}

2. 不可变集合(frozenset)

python# 创建frozenset
 frozen = frozenset([1, 2, 3, 2])
 print(frozen)  # frozenset({1, 2, 3})
  
 # frozenset不可变
 try:
     frozen.add(4)  # 会报错: AttributeError
 except AttributeError as e:
     print(f"Error: {e}")

五、布尔类型(bool)

布尔类型是整数的子类,只有两个值:True 和 False

python# 布尔值
 is_active = True
 is_empty = False
  
 print(type(is_active))  # <class 'bool'>
  
 # 布尔运算
 print(True and False)  # 与: False
 print(True or False)   # 或: True
 print(not True)        # 非: False
  
 # 布尔转换
 print(bool(0))      # False
 print(bool(1))      # True
 print(bool(""))      # False
 print(bool("hello")) # True
 print(bool([]))      # False
 print(bool([1, 2]))  # True
  
 # 实际应用中的布尔判断
 age = 18
 can_vote = age >= 18
 print(f"Can vote: {can_vote}")  # Can vote: True

六、None类型

None 表示空值或缺失值,是 NoneType 的唯一实例。

python# None示例
 result = None
 print(result is None)  # True
 print(type(result))    # <class 'NoneType'>
  
 # 函数默认返回值
 def no_return():
     pass
  
 print(no_return() is None)  # True
  
 # 作为占位符
 value = None
 # ... 稍后赋值 ...
 value = 42

七、类型检查与转换

1. 类型检查

pythonx = 42
 print(isinstance(x, int))    # True
 print(isinstance(x, float))  # False
 print(type(x) is int)        # True

2. 类型转换

python# 数值转换
 print(int("123"))    # 字符串转整数: 123
 print(float("3.14"))  # 字符串转浮点数: 3.14
 print(str(100))      # 整数转字符串: '100'
 print(complex(2, 3)) # 实数转复数: (2+3j)
  
 # 序列转换
 print(list("hello"))  # 字符串转列表: ['h', 'e', 'l', 'l', 'o']
 print(tuple([1, 2]))  # 列表转元组: (1, 2)
 print(set([1, 1, 2])) # 列表转集合: {1, 2}
  
 # 字典转换
 keys = ['a', 'b', 'c']
 values = [1, 2, 3]
 print(dict(zip(keys, values)))  # {'a': 1, 'b': 2, 'c': 3}

八、总结与最佳实践

  1. 选择正确的数据类型
  • 需要有序集合且可能修改 → 列表
  • 需要快速查找且不重复 → 集合
  • 需要键值对存储 → 字典
  • 需要不可变序列 → 元组
  • 需要固定内容 → 字符串
  1. 类型提示(Python 3.6+)

pythondef greet(name: str) -> str:
     return f"Hello, {name}"

  1. 避免类型错误

python# 不安全的操作
 try:
     result = "10" + 5
 except TypeError as e:
     print(f"Error: {e}")  # Error: can only concatenate str (not "int") to str
  
 # 安全的操作
 result = int("10") + 5
 print(result)  # 15

  1. 使用内置函数检查类型
  • type() - 返回对象的类型
  • isinstance() - 检查对象是否是特定类型或其子类
  • issubclass() - 检查一个类是否是另一个类的子类

Python的数据类型系统既灵活又强大,合理使用各种数据类型可以编写出更高效、更易读的代码。建议初学者通过实际项目练习不同数据类型的使用,逐步掌握它们的特性和最佳实践。

举报

相关推荐

0 条评论