Creating new variables in loop, with names from list, in Python

后端 未结 4 520
我寻月下人不归
我寻月下人不归 2020-12-01 19:55

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[ind         


        
相关标签:
4条回答
  • 2020-12-01 20:33

    A dictionary is the way to go!

    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())
    
    0 讨论(0)
  • 2020-12-01 20:39

    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
    
    0 讨论(0)
  • 2020-12-01 20:52
    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 讨论(0)
  • 2020-12-01 20:56

    You can use 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
    }
    
    0 讨论(0)
提交回复
热议问题