locals() 函数会以字典类型返回当前位置的全部局部变量
createVar = locals()
listTemp = [1,2,3,4]
for i,s in enumerate(listTemp):
createVar['a'+str(i+1)] = s
print(createVar,type(createVar))
print(a1,a2,a3,a4)
>>> 'execfile': <function execfile at 0x105095950>, 'runfile': <function runfile at 0x1051f01e0>, 'breakpoint': <function ptvsd_breakpointhook at 0x102c010d0>}, 'createVar': {...}, 'listTemp': [1, 2, 3, 4], 'i': 3, 's': 4, 'a1': 1, 'a2': 2, 'a3': 3, 'a4': 4} <class 'dict'>
1 2 3 4
locals()返回一个包含所有局部变量的字典,createVar指向这个字典。下面的操作就是往这个字典里添加数据了。
另一种方法:
word=[]
for i in range(4):
word.append('words_{}'.format(i))
print(word)
>>>['words_0', 'words_1', 'words_2', 'words_3']
listTemp = [1,2,3,4]
word={}
for i,s in enumerate(listTemp):
word['words_{}'.format(i)] = s
print(word)
>>> {'words_0': 1, 'words_1': 2, 'words_2': 3, 'words_3': 4}
https://www.cnblogs.com/technologylife/p/9211324.html