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

如何通过构造字符串名称简化Pandas Series的取值与赋值操作?

简洁实现方案

可以利用Python内置的getattr()函数动态获取实例属性,替代冗余的分支判断,代码会更简洁且易于扩展:

获取值函数改进

def getEntityValue(self, testCase, ent_order):
    series_name = f"testInputEnt{ent_order}"
    return getattr(self, series_name)[testCase]

赋值函数改进

def setEntityValue(self, testCase, ent_order, value):
    series_name = f"testResultEnt{ent_order}"
    getattr(self, series_name)[testCase] = value

补充说明

  • 这种方式通过字符串格式化动态拼接属性名,直接从实例中获取对应的Series对象,避免了大量重复的分支逻辑
  • 后续如果需要新增ent_order=4这类场景,无需修改函数代码,只要实例中存在对应的testInputEnt4/testResultEnt4属性即可直接支持

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 22:10:39