python附加列表递增变量名称

时间:2018-09-12 01:09:16

标签: python loops variables

我有很多变量,

df_foo_1_100 = 4
df_foo_1_1000 = 5
...
df_foo_1_1000000 = 100

df_foo_2_100 = 9 
df_foo_2_1000 = 10 
df_foo_2_1000000 = -100

df_foo_4_100 = -1000

,并且有一个空列表temp=[] 这个空列表如何使用循环保存所有变量?

这是我的代码,

index = [1,2,4,8,16,32,64]
index2 = [100, 1000, 10000, 100000, 1000000]
for i in index:
    for j in index2:
        temp.append(df_foo_{0}_{1}.format(i, j))

但是没有运气。
如何解决此循环,以便获得输出,

[df_1_100, df_1_1000... ]

(列表内部不是字符串,而是变量名称)

==========编辑========== dict也很好。 结果dict就像, {df_foo_1_100:4,df_foo_1_1000:5 ...}

谢谢!

2 个答案:

答案 0 :(得分:0)

您可以尝试提升exec功能。

index = [1,2,4,8,16,32,64]
index2 = [100, 1000, 10000, 100000, 1000000]
for i in index:
    for j in index2:
        exec("temp_variable = df_foo_{0}_{1}".format(i, j))
        temp.append(temp_variable)

答案 1 :(得分:0)

您需要某种方式来通过名称获取变量的值。您可以将它们手动添加到dict,也可以使用内置的locals()来实现。

df_foo_1_100 = "test_1_100"
df_foo_1_1000 = "test_1_1000"
df_foo_1_10000 = "test_1_10000"

df_foo_2_100 = "test_2_100"
df_foo_2_1000 = "test_2_1000"
df_foo_2_10000 = "test_2_10000"

df_foo_4_100 = "test_4_100"
df_foo_4_1000 = "test_4_1000"
df_foo_4_10000 = "test_4_10000"

df_foo_7_100 = "other_junk" # Not included...                                                                                                                                                               

import itertools
index1 = ["1", "2", "4"]
index2 = ["100", "1000", "10000"]
all_index_combos = list(itertools.product(index1, index2))
all_index_variables = set(["df_foo_{0}_{1}".format(ind1, ind2) for ind1, ind2 in all_index_combos])
dfs = [var for name, var in locals().items() if name in all_index_variables]
print(dfs)

此输出

['test_1_100', 'test_1_1000', 'test_1_10000', 'test_2_100', 'test_2_1000', 'test_2_10000', 'test_4_100', 'test_4_1000', 'test_4_10000']

根据需要。

如果您想要dict,只需更改

dfs = [var for name, var in locals().items() if name in all_index_variables]

dfs = dict([(name, var) for name, var in locals().items() if name in all_index_variables])

它将输出:

{'df_foo_1_100': 'test_1_100', 'df_foo_1_1000': 'test_1_1000', 'df_foo_1_10000': 'test_1_10000', 'df_foo_2_100': 'test_2_100', 'df_foo_2_1000': 'test_2_1000', 'df_foo_2_10000': 'test_2_10000', 'df_foo_4_100': 'test_4_100', 'df_foo_4_1000': 'test_4_1000', 'df_foo_4_10000': 'test_4_10000'}