代码之家  ›  专栏  ›  技术社区  ›  jayko03

python追加列表递增变量名

  •  0
  • jayko03  · 技术社区  · 6 年前

    我有很多变量,

    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 就像, {dfèfooèu 1èu 100:4,dfèfooèu 1èu 1000:5…}

    提前谢谢!

    2 回复  |  直到 6 年前
        1
  •  0
  •   mckuok    6 年前

    你可以试着抬高 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)
    
        2
  •  0
  •   Matt Messersmith    6 年前

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

    根据需要。

    如果你想要一个 口述

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