首页 > 解决方案 > 在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 过程中使用。

标签: python

解决方案


简短的回答:不要这样做!

这样做会破坏全局命名空间,不建议这样做。如果你真的需要这样做,可以这样做:

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']

推荐阅读