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

Python:根据循环中的值分配灵活的变量

  •  1
  • PineNuts0  · 技术社区  · 5 年前

    test = ['0to50', '51to100', '101to200', '201to10000']

    var_0to50
    var_51to100
    var_101to200
    var_201to10000
    

    test = ['0to50', '51to100', '101to200', '201to10000']
    
    for i in test:
        print (i)
    
        var_{i} = 3
    

    但这给了我一个错误:

    File "<ipython-input-76-58f6edb37b90>", line 6
        var_{i} = 3
            ^
    SyntaxError: invalid syntax
    

    2 回复  |  直到 5 年前
        1
  •  1
  •   balderman    5 年前

    你可以做个口述

    test = ['0to50', '51to100', '101to200', '201to10000']
    d = {x: 3 for x in test}
    print(d)
    

    {'0to50': 3, '51to100': 3, '101to200': 3, '201to10000': 3}
    
        2
  •  0
  •   Timur Shtatland    5 年前

    您可能需要一个字典,而不是几个动态命名的变量:

    test = ['0to50', '51to100', '101to200', '201to10000']
    dct = {}
    
    for k in test:
        print(k)
        dct[k] = 3
    
    print(dct)
        
    # 0to50
    # 51to100
    # 101to200
    # 201to10000
    # {'0to50': 3, '51to100': 3, '101to200': 3, '201to10000': 3}
    

    另请参见:
    How do I create variable variables?
    Creating multiple variables