简体   繁体   English

使用可变行和列在python中初始化二维列表

[英]Initializing 2D list in python with variable rows and columns

I have been trying to write a program in which we require to create a 2D list (array) in python with variable (not set while initialising) rows and columns.我一直在尝试编写一个程序,其中我们需要在 python 中创建一个带有变量(初始化时未设置)行和列的二维列表(数组)。 I know that in case of 1D list we can simply write:我知道在一维列表的情况下,我们可以简单地写:

a = [] a = []

in which the length is not set initially.其中最初未设置长度。 But in the case of 2D list (array) the syntax:但在二维列表(数组)的情况下,语法:

a1 = [][] a1 = [][]

is labelled incorrect (shows an error).被标记为不正确(显示错误)。 When I looked it up in the Internet, I found out that the correct syntax is:在网上查了一下,发现正确的语法是:

a1 = [[]* (some integer)]*[(some integer)] a1 = [[]*(某个整数)]*[(某个整数)]

This indeed worked, the only problem being that the dimensions of the matrix (2D array) was already set while initialising.这确实有效,唯一的问题是矩阵(二维数组)的维度在初始化时已经设置。 Would someone please help me out?有人可以帮我吗?

How I would initialize a matrix from lists in python:我将如何从 python 中的列表初始化矩阵:

w = 3
h = 3
a = []
for i in range(h):
    a.append([0]*w)

The syntax you found on the internet is incorrect as what I'm assuming it's trying to do is create a list of lists of lists, the innermost lists containing just one integer each.您在 Internet 上发现的语法不正确,因为我假设它试图做的是创建一个列表列表,最里面的列表每个只包含一个整数。 However trying to run it produces a syntax error as the brackets aren't even closed properly.但是尝试运行它会产生语法错误,因为括号甚至没有正确关闭。 Moreover, trying to initialize a matrix in one line would result in the exact same 1D list being copied multiple times in the 2D matrix, so attempting to modify one will modify every row.此外,尝试在一行中初始化矩阵会导致在 2D 矩阵中多次复制完全相同的 1D 列表,因此尝试修改一个列表将修改每一行。

Here are my methods for extending number of rows:这是我扩展行数的方法:

a.append([0]*len(a[0]))

number of columns:列数:

for i in range(len(a)):
    a[i].append(0)

However I would strongly, strongly suggest numpy in large projects as there is nothing stopping you here from modifying the length of just one row, hence corrupting your entire matrix.但是,我强烈建议在大型项目中使用 numpy,因为没有什么可以阻止您修改一行的长度,从而破坏整个矩阵。

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

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