如何在循环中创建新变量,其名称和值来自列表? [重复]

问题描述 投票:0回答:4

如何使用列表中的名称和值创建新变量?

这个:

name = ['mike', 'john', 'steve']   
age = [20, 32, 19]  
index = 0

for e in name:
    name[index] = age[index]
    index = index+1

...当然不行。我该怎么办?

我想做这个:

print mike
>>> 20

print steve
>>> 19
python list variables
4个回答
13
投票

我认为

dictionaries
更适合这个目的:

>>> name = ['mike', 'john', 'steve']   

>>> age = [20, 32, 19] 

>>> dic=dict(zip(name, age))

>>> dic['mike']
20
>>> dic['john']
32

但是如果你仍然想动态创建变量,你可以使用

globals()[]
:

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


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

5
投票

可以使用

globals()

globals()[e] = age[index]

不过,一般来说,你不想这样做;有字典就方便多了。

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

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)

0
投票

字典是最好的选择!

import pandas as pd
import datetime
import pandas_datareader as dr

# Get data for this year, so far
start = datetime.datetime(2019,1,1)
end = datetime.datetime(2019,6,1)

companies = ['AA', 'AAPL', 'BA', 'IBM']
df_dict = {}
for name in companies:
    df_dict[name] = pd.DataFrame()
    df_dict[name] = dr.data.get_data_yahoo(name, start, end)

print()
print(' Apple dataframe ')
print(df_dict['AAPL'].head())
© www.soinside.com 2019 - 2024. All rights reserved.