在Python中使用列表中的名称在循环中创建新变量

时间:2021-07-11 21:25:33

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

3 个解决方案

#1


10  

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()[]:

但是如果您仍然想要动态创建变量,可以使用globals()[]:

>>> for x,y in zip(name, age):
    globals()[x] = y


>>> mike
20
>>> steve
19
>>> john
32

#2


3  

You can use globals():

你可以使用globals():

globals()[e] = age[index]

Generally, though, you don't want to do that; a dictionary is much more convenient.

但一般来说,你不想这样做;字典更方便。

people = {
    'mike': 20,
    'john': 32,
    'steve': 19
}

#3


0  

name = ['mike', 'john', 'steve']   
age = [20, 32, 19] 
for i in range(len(name)):
    exec("%s = %d" %(name[i], age[i]))
print(mike)
print(john)
print(steve)

#1


10  

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()[]:

但是如果您仍然想要动态创建变量,可以使用globals()[]:

>>> for x,y in zip(name, age):
    globals()[x] = y


>>> mike
20
>>> steve
19
>>> john
32

#2


3  

You can use globals():

你可以使用globals():

globals()[e] = age[index]

Generally, though, you don't want to do that; a dictionary is much more convenient.

但一般来说,你不想这样做;字典更方便。

people = {
    'mike': 20,
    'john': 32,
    'steve': 19
}

#3


0  

name = ['mike', 'john', 'steve']   
age = [20, 32, 19] 
for i in range(len(name)):
    exec("%s = %d" %(name[i], age[i]))
print(mike)
print(john)
print(steve)