【问题标题】:Python: Assign Flexible Variables That Change Based on Value in LoopPython:分配基于循环值变化的灵活变量
【发布时间】:2021-03-03 20:20:04
【问题描述】:

我有一个清单:test = ['0to50', '51to100', '101to200', '201to10000']

我想使用 for 循环创建以下四个变量:

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

我做错了什么?

【问题讨论】:

  • 你不能让你的python脚本自己写。这就是你在这里尝试做的事情
  • 我不明白你的意思

标签: python for-loop variables


【解决方案1】:

你可以有一个字典

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

输出

{'0to50': 3, '51to100': 3, '101to200': 3, '201to10000': 3}

【讨论】:

    【解决方案2】:

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

    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-10
      • 2019-04-11
      • 2015-07-19
      • 1970-01-01
      • 2015-09-05
      • 1970-01-01
      • 2013-04-07
      • 1970-01-01
      相关资源
      最近更新 更多