Python : creating multiple lists

前端 未结 5 2172
渐次进展
渐次进展 2020-12-10 06:38

I\'m trying to create multiple lists like the following:

l1 = []  
l2 = []  
..  
ln = []  

Is there any way to do that?

相关标签:
5条回答
  • 2020-12-10 07:23

    What you can do is use a dictionary:

    >>> obj = {}
    >>> for i in range(1, 21):
    ...     obj['l'+str(i)] = []
    ... 
    >>> obj
    {'l18': [], 'l19': [], 'l20': [], 'l14': [], 'l15': [], 'l16': [], 'l17': [], 'l10': [], 'l11': [], 'l12': [], 'l13': [], 'l6': [], 'l7': [], 'l4': [], 'l5': [], 'l2': [], 'l3': [], 'l1': [], 'l8': [], 'l9': []}
    >>> 
    

    You can also create a list of lists using list comprehension:

    >>> obj = [[] for i in range(20)]
    >>> obj
    [[], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], []]
    >>> 
    
    0 讨论(0)
  • 2020-12-10 07:25

    You can use dictionary comprehension:

    obj = {i:[] for i in list(range(1,5))}
    
    0 讨论(0)
  • 2020-12-10 07:29

    You can simply use a for loop to create n lists.

    for i in range(10): a_i = [i] #Stores the corresponding value of i in each a_i list. print(a_i)

    The variable a_i changes as i increments, so it becomes a_1, a_2, a_3 ... and so on.

    0 讨论(0)
  • 2020-12-10 07:32

    Create a list of lists:

    lists = []
    n = 20
    for i in range(n):
        lists.append([])
    
    print lists[0] # Prints []
    print lists[19] # Prints []
    
    0 讨论(0)
  • 2020-12-10 07:44

    there is a way to do that if you want to create variables. but instead, u should use a dictionary as mentioned above. but anyway I am going to show you how to create variables as you asked.

    for i in range(num_vars):
         globals()[f'ls{i}'] = []
    
    print(ls1) # lsn should work
    
    0 讨论(0)
提交回复
热议问题