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

Python:根据循环中的值分配灵活的变量,python,for-loop,variables,Python,For Loop,Variables,我有一个列表: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 但它给了我一个错误: F

我有一个列表:
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
文件“”,第6行
var_{i}=3
^
SyntaxError:无效语法

我做错了什么?

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

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}
另请参见:

你可以有一个口述

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

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

您不能让python脚本自己编写。这就是你想在这里做的我不知道你的意思