python - 在for循环python中组合两个列表时分配变量列表名称
问题描述
我在 python 中有两个列表
targetvariables = ['a','b','c']
featurevariables = ['d','e','f']
我想创建三个列表,如下所示:
a_model = ['a','d','e','f']
b_model = ['b','d','e','f']
c_model = ['c','d','e','f']
我有大约 15 个目标变量和 100 多个特征变量,那么有没有办法在某种循环中做到这一点?我试过了,但我不知道如何从一个变化的变量中分配一个列表名称:
for idx,target in enumerate(targetvariables):
target +'_model' = targetvariables[idx] + featurevariables
SyntaxError:无法分配给操作员
最终目标是测试机器学习模型并使事情变得更容易我想简单地调用:
df[[a_model]]
然后在 ML 过程中使用。
解决方案
简短的回答:不要这样做!
这样做会破坏全局命名空间,不建议这样做。如果你真的需要这样做,可以这样做:
for target_var in targetvariables:
# access the global namespace and modify it
globals()[f'{target_var}_model'] = [target_var] + featurevariables
替代#1
不要将列表存储在变量中,而是将它们存储在容器中,例如dict
:
models = {} # create an empty dict
for target_var in targetvariables:
# the same as the last example but with 'models' instead of 'globals()'
models[f'{target_var}_model'] = [target_var] + featurevariables
然后像这样访问列表:
>>> models['a_model']
['a','d','e','f']
您还可以轻松地更改代码,以便键dict
是变量名本身,而不是“_model”。
替代#2
与其存储列表,不如使用函数动态创建它们:
def get_model(target_var):
return [target_var] + featurevariables
然后像这样访问列表:
>>> get_model('a')
['a','d','e','f']
推荐阅读
- django - 如何向 Django 用户管理页面添加操作?
- c++ - 从 C++ 17 中的字符串替换 unicode 字符的最有效方法
- python - 字段 'id' 需要一个数字,但得到了 'Student'
- marklogic - 为什么匹配时不评估嵌套实体中的属性?
- java - 如何使用 GenericJackson2JsonRedisSerializer
- prestashop - 注册后的 Prestashop 重定向
- c - 检查用破折号分隔的出生日期的有效性时,输入字符时出现错误,我无法解决该问题
- javascript - 下拉列表时如何在表格上显示名称
- arduino - SIM800l V2 每秒闪烁一次
- xslt-1.0 - 使用 XSLT1 如何简单地分配一个从 1 开始的递增值?