首页 文章

如何在Python中定义二维数组

提问于
浏览
564

我想定义一个没有初始化长度的二维数组,如下所示:

Matrix = [][]

但它不起作用......

我已经尝试了下面的代码,但它也是错误的:

Matrix = [5][5]

Error:

Traceback ...

IndexError: list index out of range

我的错是什么?

23 回答

  • 6

    使用NumPy,您可以像这样初始化空矩阵:

    import numpy as np
    mm = np.matrix([])
    

    然后追加这样的数据:

    mm = np.append(mm, [[1,2]], axis=1)
    
  • 4

    如果您希望能够将其视为2D数组,而不是被迫在列表列表中进行思考(在我看来更自然),您可以执行以下操作:

    import numpy
    Nx=3; Ny=4
    my2Dlist= numpy.zeros((Nx,Ny)).tolist()
    

    结果是一个列表(不是NumPy数组),你可以用数字,字符串等来覆盖各个位置 .

  • 2

    我正在使用我的第一个Python脚本,我对方阵示例感到有些困惑,所以我希望下面的示例可以帮助您节省一些时间:

    # Creates a 2 x 5 matrix
     Matrix = [[0 for y in xrange(5)] for x in xrange(2)]
    

    以便

    Matrix[1][4] = 2 # Valid
    Matrix[4][1] = 3 # IndexError: list index out of range
    
  • 3
    # Creates a list containing 5 lists initialized to 0
    Matrix = [[0]*5]*5
    

    请注意这个简短的表达,请参阅@ F.J的答案中的完整解释

  • 18

    这就是字典的制作!

    matrix = {}
    

    您可以通过两种方式定义 keysvalues

    matrix[0,0] = value
    

    要么

    matrix = { (0,0)  : value }
    

    结果:

    [ value,  value,  value,  value,  value],
       [ value,  value,  value,  value,  value],
       ...
    
  • 6

    A rewrite for easy reading:

    # 2D array/ matrix
    
    # 5 rows, 5 cols
    rows_count = 5
    cols_count = 5
    
    # create
    #     creation looks reverse
    #     create an array of "cols_count" cols, for each of the "rows_count" rows
    #        all elements are initialized to 0
    two_d_array = [[0 for j in range(cols_count)] for i in range(rows_count)]
    
    # index is from 0 to 4
    #     for both rows & cols
    #     since 5 rows, 5 cols
    
    # use
    two_d_array[0][0] = 1
    print two_d_array[0][0]  # prints 1   # 1st row, 1st col (top-left element of matrix)
    
    two_d_array[1][0] = 2
    print two_d_array[1][0]  # prints 2   # 2nd row, 1st col
    
    two_d_array[1][4] = 3
    print two_d_array[1][4]  # prints 3   # 2nd row, last col
    
    two_d_array[4][4] = 4
    print two_d_array[4][4]  # prints 4   # last row, last col (right, bottom element of matrix)
    
  • 798

    如果在开始之前没有大小信息,则创建两个一维列表 .

    列表1:存储行列表2:实际二维矩阵

    将整行存储在第一个列表中 . 完成后,将列表1附加到列表2中:

    from random import randint
    
    
    coordinates=[]
    temp=[]
    points=int(raw_input("Enter No Of Coordinates >"))
    for i in range(0,points):
        randomx=randint(0,1000)
        randomy=randint(0,1000)
        temp=[]
        temp.append(randomx)
        temp.append(randomy)
        coordinates.append(temp)
    
    print coordinates
    

    输出:

    Enter No Of Coordinates >4
    [[522, 96], [378, 276], [349, 741], [238, 439]]
    
  • 3

    通过使用列表:

    matrix_in_python  = [['Roy',80,75,85,90,95],['John',75,80,75,85,100],['Dave',80,80,80,90,95]]
    

    通过使用dict:您还可以将此信息存储在哈希表中以便快速搜索

    matrix = { '1':[0,0] , '2':[0,1],'3':[0,2],'4' : [1,0],'5':[1,1],'6':[1,2],'7':[2,0],'8':[2,1],'9':[2,2]};
    

    矩阵['1']会给你O(1)时间的结果

    *nb :您需要处理哈希表中的冲突

  • 0
    l=[[0]*(L) for i in range(W)]
    

    将比以下更快:

    l = [[0 for x in range(L)] for y in range(W)]
    
  • 83

    使用:

    import copy
    
    def ndlist(*args, init=0):
        dp = init
        for x in reversed(args):
            dp = [copy.deepcopy(dp) for _ in range(x)]
        return dp
    
    l = ndlist(1,2,3,4) # 4 dimensional list initialized with 0's
    l[0][1][2][3] = 1
    

    我认为NumPy是要走的路 . 如果您不想使用NumPy,以上是通用的 .

  • 275

    您应该列出一个列表,最好的方法是使用嵌套的理解:

    >>> matrix = [[0 for i in range(5)] for j in range(5)]
    >>> pprint.pprint(matrix)
    [[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]]
    

    在您的 [5][5] 示例中,您正在创建一个包含整数"5"的列表,并尝试访问其第5项,这自然会引发IndexError,因为没有第5项:

    >>> l = [5]
    >>> l[5]
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    IndexError: list index out of range
    
  • 338

    如果要创建空矩阵,则使用正确的语法

    matrix = [[]]
    

    如果你想生成一个大小为5的矩阵,填充0,

    matrix = [[0 for i in xrange(5)] for i in xrange(5)]
    
  • 67

    在Python中,您将创建一个列表列表 . 您不必提前声明尺寸,但可以 . 例如:

    matrix = []
    matrix.append([])
    matrix.append([])
    matrix[0].append(2)
    matrix[1].append(3)
    

    现在matrix [0] [0] == 2和matrix [1] [0] == 3.您还可以使用列表推导语法 . 此示例使用它两次来构建“二维列表”:

    from itertools import count, takewhile
    matrix = [[i for i in takewhile(lambda j: j < (k+1) * 10, count(k*10))] for k in range(10)]
    
  • 17

    这就是我通常在python中创建2D数组的方法 .

    col = 3
    row = 4
    array = [[0] * col for _ in range(row)]
    

    与在列表推导中使用for循环相比,我发现这种语法很容易记住 .

  • 9

    使用:

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

    第一个维度的* 5起作用,因为在此级别数据是不可变的 .

  • 9
    rows = int(input())
    cols = int(input())
    
    matrix = []
    for i in range(rows):
      row = []
      for j in range(cols):
        row.append(0)
      matrix.append(row)
    
    print(matrix)
    

    为什么这么长的代码,你问_496093?

    很久以前,当我对Python不熟悉的时候,我看到单行回答编写2D矩阵,并告诉自己我不会再在Python中使用二维矩阵 . (那些单行非常可怕,它没有给我任何有关Python正在做什么的信息 . 另请注意,我不知道这些简写 . )

    无论如何,这里是来自C,CPP和Java背景的初学者的代码

    Python爱好者和专家的注意事项:请不要因为我写了详细的代码而拒绝投票 .

  • 7

    接受的答案是好的和正确的,但我花了一段时间才明白我也可以用它来创建一个完全空的数组 .

    l =  [[] for _ in range(3)]
    

    结果是

    [[], [], []]
    
  • 4

    我用逗号分隔文件读取如下:

    data=[]
    for l in infile:
        l = split(',')
        data.append(l)
    

    列表“data”然后是具有索引数据的列表列表[row] [col]

  • 3

    如果你真的想要一个矩阵,你可能最好使用 numpy . numpy 中的矩阵运算通常使用具有两个维度的数组类型 . 创建新数组的方法有很多种;其中最有用的是 zeros 函数,它接受一个shape参数并返回给定形状的数组,其值初始化为零:

    >>> import numpy
    >>> numpy.zeros((5, 5))
    array([[ 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.]])
    

    numpy 也提供 matrix 类型 . 它不太常用,有些人使用它 . 但它对于从Matlab和其他一些环境中来到 numpy 的人来说很有用 . 我以为我正在谈论矩阵!

    >>> numpy.matrix([[1, 2], [3, 4]])
    matrix([[1, 2],
            [3, 4]])
    

    以下是创建二维数组和矩阵的一些其他方法(为了紧凑性而删除了输出):

    numpy.matrix('1 2; 3 4')                 # use Matlab-style syntax
    numpy.arange(25).reshape((5, 5))         # create a 1-d range and reshape
    numpy.array(range(25)).reshape((5, 5))   # pass a Python range and reshape
    numpy.array([5] * 25).reshape((5, 5))    # pass a Python list and reshape
    numpy.empty((5, 5))                      # allocate, but don't initialize
    numpy.ones((5, 5))                       # initialize with ones
    numpy.ndarray((5, 5))                    # use the low-level constructor
    
  • 2

    以下是初始化列表列表的简短表示法:

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

    不幸的是,缩短到像 5*[5*[0]] 这样的东西并没有真正起作用,因为你最终得到了同一个列表的5个副本,所以当你修改其中一个时它们都会改变,例如:

    >>> matrix = 5*[5*[0]]
    >>> matrix
    [[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]]
    >>> matrix[4][4] = 2
    >>> matrix
    [[0, 0, 0, 0, 2], [0, 0, 0, 0, 2], [0, 0, 0, 0, 2], [0, 0, 0, 0, 2], [0, 0, 0, 0, 2]]
    
  • 36

    声明一个零(一)个矩阵:

    numpy.zeros((x, y))
    

    例如

    >>> numpy.zeros((3, 5))
        array([[ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.]])
    

    或numpy.ones((x,y))例如

    >>> np.ones((3, 5))
    array([[ 1.,  1.,  1.,  1.,  1.],
       [ 1.,  1.,  1.,  1.,  1.],
       [ 1.,  1.,  1.,  1.,  1.]])
    

    甚至三维也是可能的 . (http://www.astro.ufl.edu/~warner/prog/python.html参见 - >多维数组)

  • 10

    您在技术上尝试索引未初始化的数组 . 在添加项目之前,您必须首先使用列表初始化外部列表; Python称之为“列表理解” .

    # Creates a list containing 5 lists, each of 8 items, all set to 0
    w, h = 8, 5;
    Matrix = [[0 for x in range(w)] for y in range(h)]
    

    您现在可以向列表中添加项目:

    Matrix[0][0] = 1
    Matrix[6][0] = 3 # error! range... 
    Matrix[0][6] = 3 # valid
    
    print Matrix[0][0] # prints 1
    x, y = 0, 6 
    print Matrix[x][y] # prints 3; be careful with indexing!
    

    虽然您可以按照自己的意愿命名它们,但我这样看是为了避免索引可能产生的混淆,如果对内部和外部列表使用“x”,并且想要非方形矩阵 .

  • 9

    如果你想要的只是一个二维容器来容纳一些元素,你可以方便地使用字典:

    Matrix = {}
    

    然后你可以这样做:

    Matrix[1,2] = 15
    print Matrix[1,2]
    

    这是有效的,因为 1,2 是一个元组,并且您将它用作索引字典的键 . 结果类似于哑稀疏矩阵 .

    如osa和Josap Valls所示,您还可以使用 Matrix = collections.defaultdict(lambda:0) ,以便缺少的元素具有默认值 0 .

    Vatsal进一步指出,这种方法对于大型矩阵可能效率不高,而且只能用于代码的非性能关键部分 .

相关问题