5

如何使用列表中的名称创建新变量?这个:

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
4

4 回答 4

12

我认为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
于 2012-07-03T22:13:59.840 回答
4

可以使用globals()

globals()[e] = age[index]

不过,一般来说,您不想这样做。字典要方便得多。

people = {
    'mike': 20,
    'john': 32,
    'steve': 19
}
于 2012-07-03T22:13:45.720 回答
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)
于 2018-06-28T20:51:19.713 回答
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())
于 2019-06-09T09:34:56.217 回答