一.元组
元组(tuple)是一种不可变的序列类型,用于存储多个有序元素。与列表(list)不同,元组一旦创建就不能修改其内容,这使得元组具有更高的安全性和性能优势,元组使用圆括号 ()
或直接用逗号分隔元素(无需括号)来定义
元组的特点:
1. 有序,可以重复,这一点和列表一样
2. 元组中的元素不能修改,这一点非常重要,深度学习场景中很多参数、形状定义好了确保后续不能被修改
二.元组操作
1.元组的创建
my_tuple1 = (1, 2, 3)
my_tuple2 = ('a', 'b', 'c')
my_tuple3 = (1, 'hello', 3.14, [4, 5]) # 可以包含不同类型的元素
print(my_tuple1)
print(my_tuple2)
print(my_tuple3)
省略括号
my_tuple4 = 10, 20, 'thirty' # 逗号是关键
print(my_tuple4)
print(type(my_tuple4)) # 看看它的类型
空元组
empty_tuple = ()
# 或者使用 tuple() 函数
empty_tuple2 = tuple()
print(empty_tuple)
print(empty_tuple2)
2.元组的常见用法
(1)元组的索引
my_tuple = ('P', 'y', 't', 'h', 'o', 'n')
print(my_tuple[0]) # 第一个元素
print(my_tuple[2]) # 第三个元素
print(my_tuple[-1]) # 最后一个元素
(2)元组的切片
my_tuple = (0, 1, 2, 3, 4, 5)
print(my_tuple[1:4]) # 从索引 1 到 3 (不包括 4)
print(my_tuple[:3]) # 从开头到索引 2
print(my_tuple[3:]) # 从索引 3 到结尾
print(my_tuple[::2]) # 每隔一个元素取一个
(3)元组的长度获取
my_tuple = (1, 2, 3)
print(len(my_tuple))
3.元组+管道
管道工程中pipeline类接收的是一个包含多个小元组的 列表 作为输入
可以这样理解这个结构:
1. 列表 [ ]: 定义了步骤执行的先后顺序。Pipeline 会按照列表中的顺序依次处理数据。之所以用列表,是未来可以对这个列表进行修改
2. 元组 ( ): 用于将每个步骤的名称和处理对象捆绑在一起。名称用于在后续访问或设置参数时引用该步骤,而对象则是实际执行数据转换或模型训练的工具。固定了操作名+操作
不用字典因为字典是无序的
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import Pipeline
from sklearn.metrics import accuracy_score
# 1. 加载数据
iris = load_iris()
X = iris.data
y = iris.target
# 2. 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
# 3. 构建管道
# 管道按顺序执行以下步骤:
# - StandardScaler(): 标准化数据(移除均值并缩放到单位方差)
# - LogisticRegression(): 逻辑回归分类器
pipeline = Pipeline([
('scaler', StandardScaler()),
('logreg', LogisticRegression())
])
# 4. 训练模型
pipeline.fit(X_train, y_train)
# 5. 预测
y_pred = pipeline.predict(X_test)
# 6. 评估模型
accuracy = accuracy_score(y_test, y_pred)
print(f"模型在测试集上的准确率: {accuracy:.2f}")
三.可迭代对象
可迭代对象 (Iterable) 是 Python 中一个非常核心的概念。简单来说,一个可迭代对象就是指那些能够一次返回其成员(元素)的对象,让你可以在一个循环(比如 for 循环)中遍历它们
Python 中有很多内置的可迭代对象,目前我们见过的类型包括:
1.序列类型(Sequence Types):
list(列表)
tuple(元组)
str(字符串)
range(范围)
2.集合类型(Set Types):
set(集合)
3.字典类型(Mapping Types):
dict(字典)
4.文件对象(File objects)
5.生成器(Generators)
6.迭代器(Iterators)本身
# 列表 (list)
print("迭代列表:")
my_list = [1, 2, 3, 4, 5]
for item in my_list:
print(item)
# 元组 (tuple)
print("迭代元组:")
my_tuple = ('a', 'b', 'c')
for item in my_tuple:
print(item)
# 字符串 (str)
print("迭代字符串:")
my_string = "hello"
for char in my_string:
print(char)
# range (范围)
print("迭代 range:")
for number in range(5): # 生成 0, 1, 2, 3, 4
print(number)
# 集合类型 (Set Types)
# 集合 (set) - 注意集合是无序的,所以每次迭代的顺序可能不同
print("迭代集合:")
my_set = {3, 1, 4, 1, 5, 9}
for item in my_set:
print(item)
# 字典 (dict) - 默认迭代时返回键 (keys)
print("迭代字典 (默认迭代键):")
my_dict = {'name': 'Alice', 'age': 30, 'city': 'Singapore'}
for key in my_dict:
print(key)
# 迭代字典的值 (values)
print("迭代字典的值:")
for value in my_dict.values():
print(value)
# 迭代字典的键值对 (items)
print("迭代字典的键值对:")
for key, value in my_dict.items(): # items方法很好用
print(f"Key: {key}, Value: {value}")
四.OS模块
1.导入
import os
# os是系统内置模块,无需安装
2.获取当前工作目录
os.getcwd() # get current working directory 获取当前工作目录的绝对路径
3.获取当前工作目录下的文件列表
os.listdir() # list directory 获取当前工作目录下的文件列表
4.拼接后获取工作目录
# 我们使用 r'' 原始字符串,这样就不需要写双反斜杠 \\,因为\会涉及到转义问题
path_a = r'C:\Users\YourUsername\Documents' # r''这个写法是写给python解释器看,他只会读取引号内的内容,不用在意r的存在会不会影响拼接
path_b = 'MyProjectData'
file = 'results.csv'
# 使用 os.path.join 将它们安全地拼接起来,os.path.join 会自动使用 Windows 的反斜杠 '\' 作为分隔符
file_path = os.path.join(path_a , path_b, file)
file_path
5.环境变量方法
# os.environ 表现得像一个字典,包含所有的环境变量
os.environ
# 使用 .items() 方法可以方便地同时获取变量名(键)和变量值,之前已经提过字典的items()方法,可以取出来键和值
# os.environ是可迭代对象
for variable_name, value in os.environ.items():
# 直接打印出变量名和对应的值
print(f"{variable_name}={value}")
# 你也可以选择性地打印总数
print(f"\n--- 总共检测到 {len(os.environ)} 个环境变量 ---")
6.目录树
os.walk() 是 Python os 模块中一个非常有用的函数,它用于遍历(或称“行走”)一个目录树
核心功能:
os.walk(top, topdown=True, οnerrοr=None, followlinks=False) 会为一个目录树生成文件名。对于树中的每个目录(包括 top 目录本身),它会 yield(产生)一个包含三个元素的元组 (tuple):(dirpath, dirnames, filenames)
1. dirpath: 一个字符串,表示当前正在访问的目录的路径
2. dirnames: 一个列表(list),包含了 dirpath 目录下所有子目录的名称(不包括 . 和 ..)
3. filenames: 一个列表(list),包含了 dirpath 目录下所有非目录文件的名称
import os
start_directory = os.getcwd() # 假设这个目录在当前工作目录下
print(f"--- 开始遍历目录: {start_directory} ---")
for dirpath, dirnames, filenames in os.walk(start_directory):
print(f" 当前访问目录 (dirpath): {dirpath}")
print(f" 子目录列表 (dirnames): {dirnames}")
print(f" 文件列表 (filenames): {filenames}")
# # 你可以在这里对文件进行操作,比如打印完整路径
# print(" 文件完整路径:")
# for filename in filenames:
# full_path = os.path.join(dirpath, filename)
# print(f" - {full_path}")