How to create and fill a list of lists in a for loop

后端 未结 6 2086
轮回少年
轮回少年 2020-12-15 01:22

I\'m trying to populate a list with a for loop. This is what I have so far:

newlist = []
for x in range(10):
    for y in range(10):
        newlist.append(y         


        
相关标签:
6条回答
  • 2020-12-15 01:39
    newlist = [list(range(10))] * 10
    
    0 讨论(0)
  • 2020-12-15 01:48

    Or just nested list comprehension

    [[x for x in range(10)] for _ in range(10)]
    
    0 讨论(0)
  • 2020-12-15 01:49

    You were close to it. But you need to append new elements in the inner loop to an empty list, which will be append as element of the outer list. Otherwise you will get (as you can see from your code) a flat list of 100 elements.

    newlist = []
    for x in range(10):
        innerlist = []
        for y in range(10):
            innerlist.append(y)
        newlist.append(innerlist)
    
    print(newlist)
    

    See the comment below by Błotosmętek for a more concise version of it.

    0 讨论(0)
  • 2020-12-15 01:53

    Alternatively, you only need one loop and append range(10).

    newlist = []
    for x in range(10):
        newlist.append(list(range(10)))
    

    Or

    newlist = [list(range(10)) for _ in range(10)]
    
    0 讨论(0)
  • 2020-12-15 01:53

    You should put a intermiate list to get another level

    newlist = []
    for x in range(10):
        temp_list = []
        for y in range(10):
            temp_list.append(y)
        newlist.append(temp_list)
    
    0 讨论(0)
  • 2020-12-15 01:54

    You can use this one line code with list comprehension to achieve the same result:

    new_list = [[i for i in range(10)] for j in range(10)]
    
    0 讨论(0)
提交回复
热议问题