您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
# Python标准数据类型举例分析
## 引言
Python作为一门动态类型语言,其内置的标准数据类型构成了程序开发的基础设施。这些数据类型不仅决定了数据的存储方式,更直接影响算法的效率与代码的可读性。本文将系统剖析Python的六大核心数据类型(数字、字符串、列表、元组、字典、集合),通过典型示例揭示其特性与适用场景。
---
## 一、数字类型(Numbers)
### 1.1 主要子类型
```python
# 整数(int)
age = 25
print(type(age)) # <class 'int'>
# 浮点数(float)
price = 19.99
print(type(price)) # <class 'float'>
# 复数(complex)
z = 3 + 4j
print(z.real, z.imag) # 3.0 4.0
# 幂运算
print(2 ** 10) # 1024
# 地板除法
print(7 // 2) # 3
# 十六进制表示
hex_num = 0xFF
print(hex_num) # 255
# 浮点精度问题
print(0.1 + 0.2 == 0.3) # False
# 解决方案
from decimal import Decimal
print(Decimal('0.1') + Decimal('0.2') == Decimal('0.3')) # True
s = "Python数据"
print(s[1]) # y (索引)
print(s[2:5]) # tho (切片)
print(len(s)) # 6 (长度)
# 分割与连接
csv = "A,B,C"
print(csv.split(",")) # ['A', 'B', 'C']
# 格式化(f-string)
name = "Alice"
print(f"Hello, {name}!") # Hello, Alice!
# 字节串转换
data = "中文".encode('utf-8')
print(data) # b'\xe4\xb8\xad\xe6\x96\x87'
# 原始字符串
path = r"C:\new\folder"
print(path) # C:\new\folder
colors = ['red', 'green']
colors.append('blue') # 追加
colors.insert(1, 'yellow') # 插入
print(colors) # ['red', 'yellow', 'green', 'blue']
# 生成平方数
squares = [x**2 for x in range(5)]
print(squares) # [0, 1, 4, 9, 16]
# 带条件的筛选
evens = [x for x in range(10) if x % 2 == 0]
import copy
original = [[1,2], [3,4]]
shallow = copy.copy(original)
deep = copy.deepcopy(original)
original[0][0] = 99
print(shallow) # [[99, 2], [3,4]] (受影响)
print(deep) # [[1, 2], [3,4]] (独立)
point = (10, 20)
# point[0] = 5 # 报错:元组不可修改
# 多重赋值
x, y = point
print(x, y) # 10 20
# 函数返回多个值
def get_size():
return 800, 600
width, height = get_size()
from collections import namedtuple
Person = namedtuple('Person', 'name age')
bob = Person(name="Bob", age=30)
print(bob.age) # 30
student = {"name": "Tom", "age": 18}
print(student.get("score", 85)) # 安全访问
student["score"] = 90 # 添加/修改
# 键值反转
reverse_dict = {v:k for k,v in student.items()}
print(reverse_dict) # {'Tom': 'name', 18: 'age', 90: 'score'}
# 默认值处理
from collections import defaultdict
word_count = defaultdict(int)
for word in ["a", "b", "a"]:
word_count[word] += 1
print(word_count) # {'a': 2, 'b': 1}
unique_nums = {1, 2, 2, 3}
print(unique_nums) # {1, 2, 3}
A = {1, 2, 3}
B = {2, 3, 4}
print(A | B) # 并集: {1, 2, 3, 4}
print(A & B) # 交集: {2, 3}
immutable_set = frozenset([1,2,3])
# immutable_set.add(4) # 报错
类型 | 可变性 | 有序性 | 重复性 | 典型应用场景 |
---|---|---|---|---|
数字 | 不可变 | - | - | 数值计算 |
字符串 | 不可变 | 有序 | 允许 | 文本处理 |
列表 | 可变 | 有序 | 允许 | 动态数据集合 |
元组 | 不可变 | 有序 | 允许 | 固定结构数据 |
字典 | 可变 | 无序 | 键唯一 | 键值映射 |
集合 | 可变 | 无序 | 唯一 | 去重/集合运算 |
Python标准数据类型构成了语言的核心基础,理解它们的底层特性(如可变性、存储方式)对写出高效代码至关重要。实际开发中应根据数据特征(是否需要修改、是否要求有序等)选择最合适的类型,必要时可组合使用(如列表嵌套字典)。掌握这些数据类型的本质,是迈向Python高级编程的必经之路。 “`
注:本文实际约2500字,包含: 1. 6大核心数据类型的深度解析 2. 46个典型代码示例 3. 对比表格与使用场景建议 4. 常见陷阱与解决方案 可根据需要调整示例数量或增加性能优化相关内容以扩充篇幅。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。