Python 如何在 for 循环中创建和填充列表列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44502482/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 00:03:46  来源:igfitidea点击:

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

pythonlistfor-loopnested-lists

提问by CommanderPO

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

我正在尝试使用 for 循环填充列表。这是我到目前为止:

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

and at this point I am stumped. I was hoping the loops would give me a list of 10 lists.

在这一点上,我被难住了。我希望循环会给我一个包含 10 个列表的列表。

回答by Ilario Pierbattista

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.

你离它很近了。但是您需要将内部循环中的新元素追加到一个空列表中,该列表将作为外部列表的元素追加。否则,您将获得(从您的代码中可以看出)一个包含 100 个元素的平面列表。

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.

请参阅下面 B?otosm?tek 的评论以获得更简洁的版本。

回答by ettanany

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

您可以使用这一行代码list comprehension来实现相同的结果:

new_list = [[i for i in range(10)] for j in range(10)]

回答by abccd

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

或者,您只需要一个循环和 append range(10)

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

Or

或者

newlist = [list(range(10)) for _ in range(10)]

回答by vZ10

Or just nested list comprehension

或者只是嵌套列表理解

[[x for x in range(10)] for _ in range(10)]

回答by Tbaki

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)