You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何避免Python函数中变量重复调用?Pandas Excel代码优化求助

优化建议

1. 简化函数参数使用(推荐方案)

你可以直接移除函数内冗余的变量赋值,同时让函数返回提取后的列表,方便后续处理——原代码的函数没有返回值,调用后无法拿到结果,这是需要补充的点:

import pandas as pd

file_path = 'C:/Users/sheet.xlsx'

def process_file(file_path):
    # 直接使用传入的参数,无需额外赋值或f-string转义
    df = pd.read_excel(file_path)
    wagon_list = df['Wagon'].tolist()
    weight_list = df['Weight'].tolist()
    return wagon_list, weight_list

# 调用函数获取结果
wagons, weights = process_file(file_path)

关键优化点:

  • 删掉file_location = file_locations这种完全冗余的赋值操作,直接使用函数参数
  • 无需用fr'{file_location}'处理路径,因为传入的参数本身就是合法字符串,pd.read_excel可直接接收
  • 让函数返回两个列表,确保后续能拿到处理后的数据

2. 使用外部全局变量(不推荐)

你确实可以在函数内直接调用外部的全局路径变量,但这种写法会大幅降低函数的复用性:

import pandas as pd

file_path = 'C:/Users/sheet.xlsx'

def process_file():
    df = pd.read_excel(file_path)
    wagon_list = df['Wagon'].tolist()
    weight_list = df['Weight'].tolist()
    return wagon_list, weight_list

# 调用函数
wagons, weights = process_file()

弊端说明:

  • 函数只能处理固定路径的文件,后续要处理其他Excel文件时,必须修改全局变量或重写函数,不符合模块化编程原则
  • 若全局变量名被意外修改,函数会直接报错,稳定性远不如参数传递的方式

额外健壮性优化

可以给函数添加基础的参数校验,提前规避文件不存在、表格缺列等错误:

import pandas as pd
from pathlib import Path

def process_file(file_path):
    # 检查文件是否存在
    if not Path(file_path).exists():
        raise FileNotFoundError(f"指定文件不存在:{file_path}")
    df = pd.read_excel(file_path)
    # 检查表格是否包含必要列
    required_cols = ['Wagon', 'Weight']
    missing_cols = [col for col in required_cols if col not in df.columns]
    if missing_cols:
        raise ValueError(f"表格缺少必要列:{', '.join(missing_cols)}")
    return df['Wagon'].tolist(), df['Weight'].tolist()

内容的提问来源于stack exchange,提问作者PStavis

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 15:05:16