简体   繁体   English

不确定二维列表如何在python中工作

[英]unsure of how 2-d lists work in python

Need to make a 6x8 matrix. 需要制作一个6x8矩阵。 In this matrix, need to assign values to various cells within the matrix and then simulate a heating/cooling system. 在此矩阵中,需要为矩阵中的各个单元分配值,然后模拟加热/冷却系统。 Before I get there though, I need to make sure this is right. 在到达那里之前,我需要确保这是正确的。 Is this how you make rows and columns? 这是您制作行和列的方式吗? Does it matter that it does not display this way when printed? 打印时不以这种方式显示是否重要? Like I said I need to assign values to each of theses cells, does it matter that some already have a value by the way I made the lists? 就像我说的那样,我需要为这些单元格中的每个单元格分配值,在我制作列表的方式中有些已经具有值是否重要? Is there a way to make the list without any initial values? 有没有一种方法可以使列表没有任何初始值?

matrix = [] # Create an empty list
numberOfRows = 6
numberOfColumns = 8
for row in range(0, numberOfRows):
    matrix.append([]) # Add an empty new row
    for column in range(0, numberOfColumns):
        matrix[row].append(column)

print(matrix) 



[[0, 1, 2, 3, 4, 5, 6, 7], [0, 1, 2, 3, 4, 5, 6, 7], [0, 1, 2, 3, 4, 5, 6, 7], [0, 1, 2, 3, 4, 5, 6, 7], [0, 1, 2, 3, 4, 5, 6, 7], [0, 1, 2, 3, 4, 5, 6, 7]]

Yes, it is a good method. 是的,这是一个好方法。 However, it is much easier and more pythonic to use list comprehension : matrix = [list(range(numberOfColumns)) for _ in range(numberOfRows)] 但是,使用列表理解要容易得多,也更容易使用Python: matrix = [list(range(numberOfColumns)) for _ in range(numberOfRows)]

And yes, you can make a list with no value : [] or list() 是的,您可以创建一个没有值的列表: []list()

And even a 2-dimensional list : [[]] 甚至是二维列表: [[]]

However, it has no use. 但是,它没有用。

You can use this way to make 2D arrays, but a few comments: 您可以使用这种方法制作2D阵列,但要注意以下几点:

  • You may consider initializing the elements to 0 (or -1) by changing the last line to matrix[row].append(0) . 您可以考虑通过将最后一行更改为matrix[row].append(0)来将元素初始化为0(或-1 matrix[row].append(0) This is mostly a design choice. 这主要是设计选择。 For example, if, in your program, later on you do not change the values at every position, then you will be left with old values from the initialization. 例如,如果以后在程序中不更改每个位置的值,则初始化后将保留旧值。
  • You can re-write range(0, numberOfRows) to range(numberOfRows) ; 您可以将range(0, numberOfRows)重写为range(numberOfRows) it starts from 0 by default. 默认情况下,它从0开始。
  • List comprehension, as Labo has already mentioned 如Labo所述,列表理解

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM