create lists of unique names in a for -loop in python

后端 未结 3 815
无人共我
无人共我 2020-12-15 12:05

I want to create a series of lists with unique names inside a for-loop and use the index to create the liste names. Here is what I want to do

x = [100,2,300,         


        
相关标签:
3条回答
  • 2020-12-15 12:36

    A slight variation to the other's dict-solutions is to use a defaultdict. It allows you to skip the initialisation step by invoking the chosen type's default value.

    In this case the chosen type is a list, which will give you empty lists in the dictionary:

    >>> from collections import defaultdict
    >>> d = defaultdict(list)
    >>> d[100]
    []
    
    0 讨论(0)
  • 2020-12-15 12:47

    Don't make dynamically named variables. It makes it hard to program with them. Instead, use a dict:

    x = [100,2,300,4,75]
    dct = {}
    for i in x:
        dct['lst_%s' % i] = []
    
    print(dct)
    # {'lst_300': [], 'lst_75': [], 'lst_100': [], 'lst_2': [], 'lst_4': []}
    
    0 讨论(0)
  • 2020-12-15 12:47

    Use a dictionary to hold your lists:

    In [8]: x = [100,2,300,4,75]
    
    In [9]: {i:[] for i in x}
    Out[9]: {2: [], 4: [], 75: [], 100: [], 300: []}
    

    To access each list:

    In [10]: d = {i:[] for i in x}
    
    In [11]: d[75]
    Out[11]: []
    

    And if you really want to have lst_ in each label:

    In [13]: {'lst_{}'.format(i):[] for i in x}
    Out[13]: {'lst_100': [], 'lst_2': [], 'lst_300': [], 'lst_4': [], 'lst_75': []}
    
    0 讨论(0)
提交回复
热议问题