目的:批量生成变量名,减少重复性工作,净化命名空间。
code1:
[input]:
for i in range(3):
locals()['ex_'+str(i)]=i
print 'ex_'+str(i)
[output]:
ex_0
ex_1
ex_2
[input]: print ex_0, ex_1, ex_2
[output]: 0 1 2
code2:
[input]:
names = locals()
for i in xrange(1, 3):
names['x%s'%i] = i
print x1, x2, x3
[output]: 1 2 3