Python 2.7版创建一个多维表(Python 2.7 creating a multidime

2019-07-03 23:20发布

在Python我希望有一个直观的方式来创建一个3维列表。

我想要一个(N乘N)名单。 因此,对于n = 4应该是:

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

我已经尝试使用:

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

这似乎都在创造一个参考的副本。 我也试过,但收效甚微列表生成器的天真应用:

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)]

我也尝试建立数组反复使用循环,没有成功。 我也试过这样:

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

是否有这样做的更容易或更直观的方式?

Answer 1:

我觉得你的列表中理解的版本非常接近的工作。 你不需要做任何名单乘法(不以空列表反正工作)。 这里有一个工作版本:

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


Answer 2:

看起来最简单的方法如下:

def create_empty_array_of_shape(shape):
    if shape: return [create_empty_array_of_shape(shape[1:]) for i in xrange(shape[0])]

这是为我工作



Answer 3:

我找到了这个:

Matrix = [[0 for x in xrange(5)] for x in xrange(5)]

现在,您可以将项目添加到列表:

Matrix[0][0] = 1
Matrix[4][0] = 5

print Matrix[0][0] # prints 1
print Matrix[4][0] # prints 5

从这里: 如何定义蟒蛇二维数组



Answer 4:

这个怎么样:

class MultiDimList(object):
    def __init__(self, shape):
        self.shape = shape
        self.L = self._createMultiDimList(shape)
    def get(self, ind):
        if(len(ind) != len(self.shape)): raise IndexError()
        return self._get(self.L, ind)
    def set(self, ind, val):
        if(len(ind) != len(self.shape)): raise IndexError()
        return self._set(self.L, ind, val)
    def _get(self, L, ind):
        return self._get(L[ind[0]], ind[1:]) if len(ind) > 1 else L[ind[0]]
    def _set(self, L, ind, val):
        if(len(ind) > 1): 
            self._set(L[ind[0]], ind[1:], val) 
        else: 
            L[ind[0]] = val
    def _createMultiDimList(self, shape):
        return [self._createMultiDimList(shape[1:]) if len(shape) > 1 else None for _ in range(shape[0])]
    def __repr__(self):
        return repr(self.L)

然后,您可以使用它,如下所示

L = MultiDimList((3,4,5)) # creates a 3x4x5 list
L.set((0,0,0), 1)
L.get((0,0,0))


Answer 5:

我很惊讶,没有人试图设计一种通用的方法来做到这一点。 看到这里我的答案: https://stackoverflow.com/a/33460217/5256940

import copy

def ndlist(init, *args):  # python 2 doesn't have kwarg after *args
    dp = init
    for x in reversed(args):
        dp = [copy.deepcopy(dp) for _ in xrange(x)] # Python 2 xrange
    return dp

l = ndlist(0, 1, 2, 3, 4) # 4 dimensional list initialized with 0's
l[0][1][2][3] = 1

编辑:建立在user2114402的回答是:添加默认值参数

def ndlist(s, v):
    return [ndlist(s[1:], v) for i in xrange(s[0])] if s else v


Answer 6:

一个非常简单而优雅的方式是:

a = [([0] * 5) for i in range(5)]
a
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]


Answer 7:

在Python中我做了一个小工厂方法来创建每个这些方面的可变尺寸和可变尺寸的列表:

def create_n_dimensional_matrix(self, n):
  dimensions = len(n)
  if (dimensions == 1): 
    return [0 for i in range(n[0])]

  if (dimensions == 2): 
    return [[0 for i in range(n[0])] for j in range(n[1])]

  if (dimensions == 3): 
    return [[[0 for i in range(n[0])] for j in range(n[1])] for k in range(n[2])]

  if (dimensions == 4): 
    return [[[[0 for i in range(n[0])] for j in range(n[1])] for k in range(n[2])] for l in range(n[3])]

像这样运行它:

print(str(k.create_n_dimensional_matrix([2,3])))
print(str(k.create_n_dimensional_matrix([3,2])))
print(str(k.create_n_dimensional_matrix([1,2,3])))
print(str(k.create_n_dimensional_matrix([3,2,1])))
print(str(k.create_n_dimensional_matrix([2,3,4,5])))
print(str(k.create_n_dimensional_matrix([5,4,3,2])))    

它打印:

  1. 二维列表(2×3),(3×2)
  2. 三维列表(1x2x3),(3x2x1)
  3. 四维列表(2x3x4x5),(5x4x3x2)

     [[0, 0], [0, 0], [0, 0]] [[0, 0, 0], [0, 0, 0]] [[[0], [0]], [[0], [0]], [[0], [0]]] [[[0, 0, 0], [0, 0, 0]]] [[[[0, 0], [0, 0], [0, 0]], [[0, 0], [0, 0], [0, 0]], [[0, 0], [0, 0], [0, 0]], [[0, 0], [0, 0], [0, 0]]], [[[0, 0], [0, 0], [0, 0]], [[0, 0], [0, 0], [0, 0]], [[0, 0], [0, 0], [0, 0]], [[0, 0], [0, 0], [0, 0]]], [[[0, 0], [0, 0], [0, 0]], [[0, 0], [0, 0], [0, 0]], [[0, 0], [0, 0], [0, 0]], [[0, 0], [0, 0], [0, 0]]], [[[0, 0], [0, 0], [0, 0]], [[0, 0], [0, 0], [0, 0]], [[0, 0], [0, 0], [0, 0]], [[0, 0], [0, 0], [0, 0]]], [[[0, 0], [0, 0], [0, 0]], [[0, 0], [0, 0], [0, 0]], [[0, 0], [0, 0], [0, 0]], [[0, 0], [0, 0], [0, 0]]]] [[[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]], [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]], [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]], [[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]], [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]], [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]]] 


Answer 8:

import copy
dimensions = 2, 3, 4
z = 0
genList = lambda size,value: [copy.deepcopy(value) for i in range(size)]
for i in dimensions: z = genList(i, z)


Answer 9:

这里有一个会给你填了一个可复制的对象的拷贝一个N维“矩阵”。

编辑 :这是pterodragon的原来的答案,我更喜欢user2114402的少读答题的轻微的修改。 事实上,DOC串之外,从pterodragon的解决方案,唯一的区别是,我明确地使用尺寸大小的列表,而不是让用户它们作为参数传递。

import copy

    def instantiate_mdl(dim_maxes, base=0):
        """ Instantiate multi-dimensional list, that is a list of list of list ...

        Arguments:
            dim_maxes (list[int]): a list of dimension sizes, for example 
            [2, 4] represents a matrix (represented by lists) of 2 rows and 
            4 columns.     

            base (object): an optional argument indicating the object copies
            of which will reside at the lowest level in the datastructure.
        Returns:
            base (list[base]): a multi-dimensional list of lists structure,
            which is filled with clones of the base parameter.
        """
        for dim_max in reversed(dim_maxes):
            base = [copy.deepcopy(base) for i in range(dim_max)]
        return base

data = instantiate_mdl([3, 5])
data[0][0] = 99999
data[1][1] = 88888
data[2][4] = 77777

for r in data:
    print(r)

>>> # Output
>>> [99999, 0, 0, 0, 0]
>>> [0, 88888, 0, 0, 0]
>>> [0, 0, 0, 0, 77777]


Answer 10:

下面是做这件事的更通用的方法。

def ndlist(shape, dtype=list):
    t = '%s for v%d in xrange(shape[%d])'
    cmd = [t % ('%s', i + 1, i) for i in xrange(len(shape))]
    cmd[-1] = cmd[-1] % str(dtype())
    for i in range(len(cmd) - 1)[::-1]:
        cmd[i] = cmd[i] % ('[' + cmd[i + 1]  + ']')
    return eval('[' + cmd[0] + ']')

list_4d = ndlist((2, 3, 4))
list_3d_int = ndlist((2, 3, 4), dtype=int)

print list_4d
print list_3d_int

结果:

[[[[], [], [], []], [[], [], [], []], [[], [], [], []]], [[[], [], [], []], [[], [], [], []], [[], [], [], []]]]
[[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]], [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]]


文章来源: Python 2.7 creating a multidimensional list