如何初始化Python中的二维数组(如果不使用Numpy的列表)?
我正在开始Python,并且正在尝试使用二维列表,最初我在每个地方都用相同的变量填充。我想到了这一点:
def initialize_twodlist(foo):
twod_list = []
new = []
for i in range (0, 10):
for j in range (0, 10):
new.append(foo)
twod_list.append(new)
new = []
它给出了理想的结果,但感觉就像是解决方法。是否可以更轻松/更短/更优雅的方式来做到这一点?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(30)
代码:
initial_val
必须不可变。Code:
initial_val
must be immutable.对于每个元素,将创建一个新的
[0]*10
。for each element a new
[0]*10
will be created ..方法不正确:[[[none*m]*n]
使用这种方法,Python不允许为外柱创建不同的地址空间,并且会导致与您的期望相比各种行为。
正确的方法,但除了例外:
这是很好的方法,但是如果将默认值设置为
none
,则有例外,因此使用此方法正确设置默认值。
绝对正确:
请按照Mike的答复 double loop 。
Incorrect Approach: [[None*m]*n]
With this approach, python does not allow creating different address space for the outer columns and will lead to various misbehaviour than your expectation.
Correct Approach but with exception:
It is good approach but there is exception if you set default value to
None
So set your default value properly using this approach.
Absolute correct:
Follow the mike's reply of double loop.
初始化二维数组的使用:
arr = [[]*m for I in range(n)]
实际上,
arr = [[]*m]*n
将创建一个2D数组,其中所有N数组都指向同一数组,因此任何元素中的任何值的任何更改都会反映在所有n列表中,以获取更多信息进一步说明访问:
To initialize a 2-dimensional array use:
arr = [[]*m for i in range(n)]
actually,
arr = [[]*m]*n
will create a 2D array in which all n arrays will point to same array, so any change in value in any element will be reflected in all n listsfor more further explanation visit : https://www.geeksforgeeks.org/python-using-2d-arrays-lists-the-right-way/
使用最简单的想法来创建这个。
并添加大小:
或者如果我们想首先声明大小。我们只使用:
use the simplest think to create this.
and add the size:
or if we want to declare the size firstly. we only use:
初始化一个大小为m x n的2D矩阵,0
Initializing a 2D matrix of size m X n with 0
我使用它来创建
mxn
矩阵其中m = m = number(行)
和n = number(列(列)
。I use it this way to create
MxN
matrix wherem = number(rows)
andn = number(columns)
.如果使用 numpy ,可以轻松创建2D数组:
x
If you use numpy, you can easily create 2d arrays:
x
以上将为您提供一个
使用嵌套列表理解的5x5 2D数组。
如下:
[x]*col->评估的最终表达
对于x in - > x将是迭代器提供的值
[B范围内的B(行)]] - >迭代器。
[b对于范围(row)]]这将评估为[0,1,2,3,4],因为行= 5
为
因此,现在它简化
[[0]*5对于[0,1,1,2,3,4]] - > x = 0 1st迭代
[[1]*5对于[0,1,2,3,4]] - > x = 1 2迭代
[[2]*5 for x in [0,1,2,3,4]] - > x = 2 3迭代
[[3]*5 for x in [0,1,2,3,4]] - > x = 3第四迭代
[[4]*5 for x in [0,1,2,3,4]] - > x = 4第五迭代
The above will give you a 5x5 2D array
It is using nested list comprehension.
Breakdown as below:
[x]*col --> final expression that is evaluated
for x in --> x will be the value provided by the iterator
[b for b in range(row)]] --> Iterator.
[b for b in range(row)]] this will evaluate to [0,1,2,3,4] since row=5
so now it simplifies to
This will evaluate to
[[0]*5 for x in [0,1,2,3,4]] --> with x=0 1st iteration
[[1]*5 for x in [0,1,2,3,4]] --> with x=1 2nd iteration
[[2]*5 for x in [0,1,2,3,4]] --> with x=2 3rd iteration
[[3]*5 for x in [0,1,2,3,4]] --> with x=3 4th iteration
[[4]*5 for x in [0,1,2,3,4]] --> with x=4 5th iteration
正如@arnab和@mike指出的那样,数组不是列表。很少有差异是1)阵列在初始化期间的固定尺寸2)数组通常比列表相比支持较少的操作。
在大多数情况下,也许是过度杀伤力,但这是使用Python CTypes(C库)利用硬件阵列实现的基本2D数组实现
As @Arnab and @Mike pointed out, an array is not a list. Few differences are 1) arrays are fixed size during initialization 2) arrays normally support lesser operations than a list.
Maybe an overkill in most cases, but here is a basic 2d array implementation that leverages hardware array implementation using python ctypes(c libraries)
这是一个更简单的方法:
使用任何“ x”值初始化所有单元格:
Here is an easier way :
For initializing all cells with any 'x' value use :
可以以以下方式初始化一个空的2D矩阵:
temp = [[],[]]
An empty 2D matrix may be initialized in the following manner:
temp=[[],[]]
这是我发现新程序员的最好的,而没有使用其他库。我想要更好的东西。
This is the best I've found for teaching new programmers, and without using additional libraries. I'd like something better though.
通常,我使用此方法来初始化二维数组
n = [[int()in input()。split()。
Often I use this approach for initializing a 2-dimensional array
n=[[int(x) for x in input().split()] for i in range(int(input())]
可以从该系列中得出要添加维度的一般模式:
The general pattern to add dimensions could be drawn from this series:
我了解的重要一件事是:在初始化数组(在任何维度上)时,我们应该为所有数组的所有位置给出默认值。然后只有初始化才能完成。之后,我们可以将新值更改或接收到数组的任何位置。以下代码非常适合我
The important thing I understood is: While initializing an array(in any dimension) We should give a default value to all the positions of array. Then only initialization completes. After that, we can change or receive new values to any position of the array. The below code worked for me perfectly
另一种方法是使用词典保存二维数组。
这只是可以容纳任何1D,2D值,并将其初始化为
0
或任何其他INT值,请使用 collections 。Another way is to use a dictionary to hold a two-dimensional array.
This just can hold any 1D, 2D values and to initialize this to
0
or any other int value, use collections.初始化所有矩阵M =行,n =列
initialize all matrix m=rows and n=columns
要初始化Python中的二维列表,请使用
但不要使用
[[V]*n]*n
,这是一个陷阱!To initialize a two-dimensional list in Python, use
But don't use
[[v]*n]*n
, it is a trap!Python经常出现的一种模式
有助于激发列表综合的引入,这些模式将摘要转换为
较短,有时更清晰。通常,您会养成识别这些习惯,并经常用综合替代循环。
您的代码遵循此模式两次
A pattern that often came up in Python was
which helped motivate the introduction of list comprehensions, which convert that snippet to
which is shorter and sometimes clearer. Usually, you get in the habit of recognizing these and often replacing loops with comprehensions.
Your code follows this pattern twice
您可以使用 list consections :
You can use a list comprehension:
这种方式比嵌套列表的理解更快
,这里是一些python3时间安排,对于小列表,大小列表
说明:
[[FOO]*10]*10
创建一个列表相同的对象重复10次。您不能仅使用此功能,因为修改一个元素将在每一行中修改相同的元素!x [:]
等效于list(x)
,但效率更高,因为它避免了名称查找。无论哪种方式,它都会创建每行的浅副本,因此现在所有元素都是独立的。所有元素都是相同的
foo
对象,因此,如果foo
是可变的,您无法使用此方案。使用或假设返回
foo
s的类(或函数)foo
This way is faster than the nested list comprehensions
Here are some python3 timings, for small and large lists
Explanation:
[[foo]*10]*10
creates a list of the same object repeated 10 times. You can't just use this, because modifying one element will modify that same element in each row!x[:]
is equivalent tolist(X)
but is a bit more efficient since it avoids the name lookup. Either way, it creates a shallow copy of each row, so now all the elements are independent.All the elements are the same
foo
object though, so iffoo
is mutable, you can't use this scheme., you'd have to useor assuming a class (or function)
Foo
that returnsfoo
s在Python中初始化二维阵列:
To initialize a two-dimensional array in Python:
通常,当您想要多维阵列时,您不需要列表列表,而是一个numpy数组或可能的dict。
例如,使用numpy,您会做类似的事情
Usually when you want multidimensional arrays you don't want a list of lists, but rather a numpy array or possibly a dict.
For example, with numpy you would do something like
为什么
[['']*m]*n
不好。对于那些感到困惑的人, ”或“通过分配呼叫”。 info )
最佳方法是
[[''for range(列)的j in range(行)]
这将解决所有问题。
为了获得更多澄清
例子:
For those who are confused why
[['']*m]*n
is not good to use.Python uses a system known as “Call by Object Reference” or “Call by assignment”.(More info)
Best way is
[['' for i in range(columns)] for j in range(rows)]
This will solve all the problems.
For more Clarification
Example:
您可以做到这一点:
例如:
但这具有不希望的副作用:
You can do just this:
For example:
But this has a undesired side effect:
对于n,是行的数量,m是列的数量,而foo是值。
for n is number of rows, and m is the number of column, and foo is the value.
如果它是一个稀疏的人口组成的阵列,则最好使用带有元组键入的字典:
If it's a sparsely-populated array, you might be better off using a dictionary keyed with a tuple: