Python 2.7创建多维列表 [英] Python 2.7 creating a multidimensional list

查看:83
本文介绍了Python 2.7创建多维列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python中,我想要一种直观的方式来创建3维列表.

In Python I want an intuitive way to create a 3 dimensional list.

我想要一个(一个n个)列表.因此,对于n = 4,应为:

I want an (n by n) list. So for n = 4 it should be:

x = [[[],[],[],[]],[[],[],[],[]],[[],[],[],[]],[[],[],[],[]]]

我尝试使用:

y = [n*[n*[]]]    
y = [[[]]* n for i in range(n)]

两者似乎都在创建参考的副本. 我还尝试了列表生成器的幼稚应用程序,但收效甚微:

Which both appear to be creating copies of a reference. I've also tried naive application of the list builder with little success:

y = [[[]* n for i in range(n)]* n for i in range(n)]
y = [[[]* n for i in range(1)]* n for i in range(n)]

我还尝试使用循环迭代地构建数组,但没有成功.我也尝试过这个:

I've also tried building up the array iteratively using loops, with no success. I also tried this:

y = []
for i in range(0,n):
    y.append([[]*n for i in range(n)])

有没有更简单或更直观的方法?

Is there an easier or more intuitive way of doing this?

推荐答案

我认为您的列表理解版本非常有效.您无需进行任何列表乘法(无论如何对空列表都无效).这是一个工作版本:

I think your list comprehension versions were very close to working. You don't need to do any list multiplication (which doesn't work with empty lists anyway). Here's a working version:

>>> y = [[[] for i in range(n)] for i in range(n)]
>>> print y
[[[], [], [], []], [[], [], [], []], [[], [], [], []], [[], [], [], []]]

这篇关于Python 2.7创建多维列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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