如何在for循环中创建和填充列表列表 [英] How to create and fill a list of lists in a for loop

查看:123
本文介绍了如何在for循环中创建和填充列表列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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)

在这一点上,我很沮丧.我希望循环能给我10个列表的列表.

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

推荐答案

您离它很近.但是您需要将内部循环中的新元素追加到一个空列表,该列表将作为外部列表的元素追加.否则,您将(从代码中看到)得到一个由100个元素组成的平面列表.

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)

请参阅以下Błotosmętek的评论,以获得更简洁的版本.

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

这篇关于如何在for循环中创建和填充列表列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆