在 Python 中使用列表中的名称在循环中创建新变量 [英] Creating new variables in loop, with names from list, in Python
本文介绍了在 Python 中使用列表中的名称在循环中创建新变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何使用列表中的名称创建新变量?这:
name = ['mike', 'john', 'steve']年龄 = [20, 32, 19]指数 = 0对于 e 名称:姓名[索引] = 年龄[索引]指数=指数+1
当然不行.我该怎么办?
我想这样做:
打印麦克>>>20印刷史蒂夫>>>19
解决方案
我觉得dictionaries
更适合这个目的:
但如果你仍然想动态创建变量,你可以使用 globals()[]
:
How to create new variables with names from list? This:
name = ['mike', 'john', 'steve']
age = [20, 32, 19]
index = 0
for e in name:
name[index] = age[index]
index = index+1
of course does not work. What should I do?
I want to do this:
print mike
>>> 20
print steve
>>> 19
解决方案
I think dictionaries
are more suitable for this purpose:
>>> name = ['mike', 'john', 'steve']
>>> age = [20, 32, 19]
>>> dic=dict(zip(name, age))
>>> dic['mike']
20
>>> dic['john']
32
But if you still want to create variables on the fly you can use globals()[]
:
>>> for x,y in zip(name, age):
globals()[x] = y
>>> mike
20
>>> steve
19
>>> john
32
这篇关于在 Python 中使用列表中的名称在循环中创建新变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文