# Python 数据类型

# 基本数据类型

# 1. 数字类型

# 整数(int)

# 整数示例
x = 10
y = -5
z = 0

# 浮点数(float)

# 浮点数示例
pi = 3.14159
temperature = -2.5

# 复数(complex)

# 复数示例
c = 3 + 4j

# 2. 字符串(str)

# 字符串创建
name = "Python"
multiline = """这是一个
多行字符串"""

# 字符串操作
print(name[0])      # 索引
print(name[1:4])    # 切片
print(len(name))    # 长度
print(name.upper()) # 转大写

# 3. 布尔类型(bool)

# 布尔值
is_active = True
is_empty = False

# 比较运算
print(5 > 3)    # True
print(10 == 20) # False

# 容器类型

# 1. 列表(list)

# 列表创建
fruits = ['apple', 'banana', 'orange']
numbers = [1, 2, 3, 4, 5]

# 列表操作
fruits.append('grape')     # 添加元素
fruits.remove('banana')    # 删除元素
print(fruits[0])          # 访问元素
print(len(fruits))        # 列表长度

# 2. 元组(tuple)

# 元组创建
coordinates = (10, 20)
colors = ('red', 'green', 'blue')

# 元组操作
print(coordinates[0])     # 访问元素
print(len(colors))        # 元组长度

# 3. 字典(dict)

# 字典创建
person = {
    'name': 'John',
    'age': 30,
    'city': 'New York'
}

# 字典操作
print(person['name'])     # 访问值
person['email'] = 'john@example.com'  # 添加键值对
del person['age']         # 删除键值对
print(person.keys())      # 获取所有键

# 4. 集合(set)

# 集合创建
numbers = {1, 2, 3, 4, 5}
letters = set(['a', 'b', 'c'])

# 集合操作
numbers.add(6)           # 添加元素
numbers.remove(1)        # 删除元素
print(1 in numbers)      # 成员测试

# 类型转换

# 字符串转换
str(123)        # '123'
str(3.14)       # '3.14'
str(True)       # 'True'

# 数值转换
int('123')      # 123
float('3.14')   # 3.14

# 容器类型转换
list('Python')   # ['P', 'y', 't', 'h', 'o', 'n']
tuple([1, 2, 3]) # (1, 2, 3)
set([1, 2, 2])   # {1, 2}

# 数据类型判断

# type()函数
print(type(123))        # <class 'int'>
print(type('Python'))   # <class 'str'>
print(type([1, 2, 3]))  # <class 'list'>

# isinstance()函数
print(isinstance(123, int))        # True
print(isinstance('Python', str))   # True
print(isinstance([1, 2, 3], list)) # True

# 最佳实践

  1. 选择合适的数据类型

    • 使用列表存储可变序列数据
    • 使用元组存储不可变序列数据
    • 使用字典存储键值对数据
    • 使用集合存储唯一元素
  2. 类型转换注意事项

    • 确保转换是有效的
    • 处理可能的转换异常
    • 注意精度损失
  3. 性能考虑

    • 选择合适的数据结构
    • 注意大数据集的内存使用
    • 适当使用生成器和迭代器

# 练习题

  1. 创建并操作不同类型的数据结构
  2. 进行各种类型转换
  3. 实现简单的数据处理任务

# 下一步

继续学习Python的控制结构,包括条件语句、循环和函数定义。