如何在Python中初始化二维数组?

问题:如何在Python中初始化二维数组?

我开始使用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 = []

它给出了预期的结果,但是感觉像是一种解决方法。有没有更简单/更短/更优雅的方式来做到这一点?

I’m beginning python and I’m trying to use a two-dimensional list, that I initially fill up with the same variable in every place. I came up with this:

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 = []

It gives the desired result, but feels like a workaround. Is there an easier/shorter/more elegant way to do this?


回答 0

Python中经常出现的一种模式是

bar = []
for item in some_iterable:
    bar.append(SOME EXPRESSION)

这有助于激励列表理解的引入,从而将代码段转换为

bar = [SOME EXPRESSION for item in some_iterable]

它更短,有时更清晰。通常,您养成识别这些习惯的习惯,并经常用理解代替循环。

您的代码两次遵循此模式

twod_list = []                                       \                      
for i in range (0, 10):                               \
    new = []                  \ can be replaced        } this too
    for j in range (0, 10):    } with a list          /
        new.append(foo)       / comprehension        /
    twod_list.append(new)                           /

A pattern that often came up in Python was

bar = []
for item in some_iterable:
    bar.append(SOME EXPRESSION)

which helped motivate the introduction of list comprehensions, which convert that snippet to

bar = [SOME EXPRESSION for item in some_iterable]

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

twod_list = []                                       \                      
for i in range (0, 10):                               \
    new = []                  \ can be replaced        } this too
    for j in range (0, 10):    } with a list          /
        new.append(foo)       / comprehension        /
    twod_list.append(new)                           /

回答 1

您可以使用列表推导

x = [[foo for i in range(10)] for j in range(10)]
# x is now a 10x10 array of 'foo' (which can depend on i and j if you want)

You can use a list comprehension:

x = [[foo for i in range(10)] for j in range(10)]
# x is now a 10x10 array of 'foo' (which can depend on i and j if you want)

回答 2

这种方法比嵌套列表理解要快

[x[:] for x in [[foo] * 10] * 10]    # for immutable foo!

这是一些python3时序,适用于大小清单

$python3 -m timeit '[x[:] for x in [[1] * 10] * 10]'
1000000 loops, best of 3: 1.55 usec per loop

$ python3 -m timeit '[[1 for i in range(10)] for j in range(10)]'
100000 loops, best of 3: 6.44 usec per loop

$ python3 -m timeit '[x[:] for x in [[1] * 1000] * 1000]'
100 loops, best of 3: 5.5 msec per loop

$ python3 -m timeit '[[1 for i in range(1000)] for j in range(1000)]'
10 loops, best of 3: 27 msec per loop

说明:

[[foo]*10]*10创建重复10次的同一对象的列表。您不能只使用它,因为修改一个元素会修改每一行中的相同元素!

x[:]等效于,list(X)但效率更高,因为它避免了名称查找。无论哪种方式,它都会为每行创建一个浅表副本,因此现在所有元素都是独立的。

foo尽管所有元素都是同一个对象,所以如果foo是mutable,则不能使用此方案。必须使用

import copy
[[copy.deepcopy(foo) for x in range(10)] for y in range(10)]

或假设某个类(或函数)Foo返回foos

[[Foo() for x in range(10)] for y in range(10)]

This way is faster than the nested list comprehensions

[x[:] for x in [[foo] * 10] * 10]    # for immutable foo!

Here are some python3 timings, for small and large lists

$python3 -m timeit '[x[:] for x in [[1] * 10] * 10]'
1000000 loops, best of 3: 1.55 usec per loop

$ python3 -m timeit '[[1 for i in range(10)] for j in range(10)]'
100000 loops, best of 3: 6.44 usec per loop

$ python3 -m timeit '[x[:] for x in [[1] * 1000] * 1000]'
100 loops, best of 3: 5.5 msec per loop

$ python3 -m timeit '[[1 for i in range(1000)] for j in range(1000)]'
10 loops, best of 3: 27 msec per loop

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 to list(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 if foo is mutable, you can’t use this scheme., you’d have to use

import copy
[[copy.deepcopy(foo) for x in range(10)] for y in range(10)]

or assuming a class (or function) Foo that returns foos

[[Foo() for x in range(10)] for y in range(10)]

回答 3

不要使用[[v]*n]*n,这是一个陷阱!

>>> a = [[0]*3]*3
>>> a
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
>>> a[0][0]=1
>>> a
[[1, 0, 0], [1, 0, 0], [1, 0, 0]]

    t = [ [0]*3 for i in range(3)]

效果很好。

Don’t use [[v]*n]*n, it is a trap!

>>> a = [[0]*3]*3
>>> a
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
>>> a[0][0]=1
>>> a
[[1, 0, 0], [1, 0, 0], [1, 0, 0]]

but

    t = [ [0]*3 for i in range(3)]

works great.


回答 4

在Python中初始化二维数组:

a = [[0 for x in range(columns)] for y in range(rows)]

To initialize a two-dimensional array in Python:

a = [[0 for x in range(columns)] for y in range(rows)]

回答 5

[[foo for x in xrange(10)] for y in xrange(10)]
[[foo for x in xrange(10)] for y in xrange(10)]

回答 6

通常,当您需要多维数组时,您不需要列表列表,而是想要一个numpy数组或一个dict。

例如,使用numpy,您将执行以下操作

import numpy
a = numpy.empty((10, 10))
a.fill(foo)

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

import numpy
a = numpy.empty((10, 10))
a.fill(foo)

回答 7

您可以这样做:

[[element] * numcols] * numrows

例如:

>>> [['a'] *3] * 2
[['a', 'a', 'a'], ['a', 'a', 'a']]

但这有不希望的副作用:

>>> b = [['a']*3]*3
>>> b
[['a', 'a', 'a'], ['a', 'a', 'a'], ['a', 'a', 'a']]
>>> b[1][1]
'a'
>>> b[1][1] = 'b'
>>> b
[['a', 'b', 'a'], ['a', 'b', 'a'], ['a', 'b', 'a']]

You can do just this:

[[element] * numcols] * numrows

For example:

>>> [['a'] *3] * 2
[['a', 'a', 'a'], ['a', 'a', 'a']]

But this has a undesired side effect:

>>> b = [['a']*3]*3
>>> b
[['a', 'a', 'a'], ['a', 'a', 'a'], ['a', 'a', 'a']]
>>> b[1][1]
'a'
>>> b[1][1] = 'b'
>>> b
[['a', 'b', 'a'], ['a', 'b', 'a'], ['a', 'b', 'a']]

回答 8

twod_list = [[foo for _ in range(m)] for _ in range(n)]

因为n是行数,m是列数,foo是值。

twod_list = [[foo for _ in range(m)] for _ in range(n)]

for n is number of rows, and m is the number of column, and foo is the value.


回答 9

如果它是一个人口稀少的数组,那么最好使用以元组为键的字典:

dict = {}
key = (a,b)
dict[key] = value
...

If it’s a sparsely-populated array, you might be better off using a dictionary keyed with a tuple:

dict = {}
key = (a,b)
dict[key] = value
...

回答 10

t = [ [0]*10 for i in [0]*10]

为每个元素[0]*10创建一个新的..

t = [ [0]*10 for i in [0]*10]

for each element a new [0]*10 will be created ..


回答 11

错误的方法:[[None * m] * n]

>>> m, n = map(int, raw_input().split())
5 5
>>> x[0][0] = 34
>>> x
[[34, None, None, None, None], [34, None, None, None, None], [34, None, None, None, None], [34, None, None, None, None], [34, None, None, None, None]]
>>> id(x[0][0])
140416461589776
>>> id(x[3][0])
140416461589776

使用这种方法,python不允许为外部列创建不同的地址空间,并且会导致各种异常行为,超出您的预期。

正确的方法,但有以下exceptions:

y = [[0 for i in range(m)] for j in range(n)]
>>> id(y[0][0]) == id(y[1][0])
False

这是一个很好的方法,但是如果将默认值设置为 None

>>> r = [[None for i in range(5)] for j in range(5)]
>>> r
[[None, None, None, None, None], [None, None, None, None, None], [None, None, None, None, None], [None, None, None, None, None], [None, None, None, None, None]]
>>> id(r[0][0]) == id(r[2][0])
True

因此,使用此方法正确设置默认值。

绝对正确:

按照迈克对double loop的答复。

Incorrect Approach: [[None*m]*n]

>>> m, n = map(int, raw_input().split())
5 5
>>> x[0][0] = 34
>>> x
[[34, None, None, None, None], [34, None, None, None, None], [34, None, None, None, None], [34, None, None, None, None], [34, None, None, None, None]]
>>> id(x[0][0])
140416461589776
>>> id(x[3][0])
140416461589776

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:

y = [[0 for i in range(m)] for j in range(n)]
>>> id(y[0][0]) == id(y[1][0])
False

It is good approach but there is exception if you set default value to None

>>> r = [[None for i in range(5)] for j in range(5)]
>>> r
[[None, None, None, None, None], [None, None, None, None, None], [None, None, None, None, None], [None, None, None, None, None], [None, None, None, None, None]]
>>> id(r[0][0]) == id(r[2][0])
True

So set your default value properly using this approach.

Absolute correct:

Follow the mike’s reply of double loop.


回答 12

Matrix={}
for i in range(0,3):
  for j in range(0,3):
    Matrix[i,j] = raw_input("Enter the matrix:")
Matrix={}
for i in range(0,3):
  for j in range(0,3):
    Matrix[i,j] = raw_input("Enter the matrix:")

回答 13

要初始化二维数组,请使用: arr = [[]*m for i in range(n)]

实际上, arr = [[]*m]*n将创建一个2D数组,其中所有n个数组都指向同一数组,因此任何元素中值的任何变化都将反映在所有n个列表中

有关更多详细说明,请访问:https : //www.geeksforgeeks.org/python-using-2d-arrays-lists-the-right-way/

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 lists

for more further explanation visit : https://www.geeksforgeeks.org/python-using-2d-arrays-lists-the-right-way/


回答 14

使用最简单的思想来创建这个。

wtod_list = []

并添加大小:

wtod_list = [[0 for x in xrange(10)] for x in xrange(10)]

或者如果我们想先声明尺寸。我们只使用:

   wtod_list = [[0 for x in xrange(10)] for x in xrange(10)]

use the simplest think to create this.

wtod_list = []

and add the size:

wtod_list = [[0 for x in xrange(10)] for x in xrange(10)]

or if we want to declare the size firstly. we only use:

   wtod_list = [[0 for x in xrange(10)] for x in xrange(10)]

回答 15

正如@Arnab和@Mike指出的那样,数组不是列表。几乎没有什么不同:1)数组在初始化期间固定大小; 2)数组通常支持的操作少于列表。

在大多数情况下,这可能是一个过大的杀伤力,但这是一个基本的2d数组实现,它利用python ctypes(c库)来利用硬件数组实现

import ctypes
class Array:
    def __init__(self,size,foo): #foo is the initial value
        self._size = size
        ArrayType = ctypes.py_object * size
        self._array = ArrayType()
        for i in range(size):
            self._array[i] = foo
    def __getitem__(self,index):
        return self._array[index]
    def __setitem__(self,index,value):
        self._array[index] = value
    def __len__(self):
        return self._size

class TwoDArray:
    def __init__(self,columns,rows,foo):
        self._2dArray = Array(rows,foo)
        for i in range(rows):
            self._2dArray[i] = Array(columns,foo)

    def numRows(self):
        return len(self._2dArray)
    def numCols(self):
        return len((self._2dArray)[0])
    def __getitem__(self,indexTuple):
        row = indexTuple[0]
        col = indexTuple[1]
        assert row >= 0 and row < self.numRows() \
               and col >=0 and col < self.numCols(),\
               "Array script out of range"
        return ((self._2dArray)[row])[col]

if(__name__ == "__main__"):
    twodArray = TwoDArray(4,5,5)#sample input
    print(twodArray[2,3])

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)

import ctypes
class Array:
    def __init__(self,size,foo): #foo is the initial value
        self._size = size
        ArrayType = ctypes.py_object * size
        self._array = ArrayType()
        for i in range(size):
            self._array[i] = foo
    def __getitem__(self,index):
        return self._array[index]
    def __setitem__(self,index,value):
        self._array[index] = value
    def __len__(self):
        return self._size

class TwoDArray:
    def __init__(self,columns,rows,foo):
        self._2dArray = Array(rows,foo)
        for i in range(rows):
            self._2dArray[i] = Array(columns,foo)

    def numRows(self):
        return len(self._2dArray)
    def numCols(self):
        return len((self._2dArray)[0])
    def __getitem__(self,indexTuple):
        row = indexTuple[0]
        col = indexTuple[1]
        assert row >= 0 and row < self.numRows() \
               and col >=0 and col < self.numCols(),\
               "Array script out of range"
        return ((self._2dArray)[row])[col]

if(__name__ == "__main__"):
    twodArray = TwoDArray(4,5,5)#sample input
    print(twodArray[2,3])

回答 16

我了解的重要一点是:在初始化数组(任何维度)时,我们应该为数组的所有位置提供默认值。然后,仅初始化完成。之后,我们可以更改或接收新值到数组的任何位置。下面的代码非常适合我

N=7
F=2

#INITIALIZATION of 7 x 2 array with deafult value as 0
ar=[[0]*F for x in range(N)]

#RECEIVING NEW VALUES TO THE INITIALIZED ARRAY
for i in range(N):
    for j in range(F):
        ar[i][j]=int(input())
print(ar)

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

N=7
F=2

#INITIALIZATION of 7 x 2 array with deafult value as 0
ar=[[0]*F for x in range(N)]

#RECEIVING NEW VALUES TO THE INITIALIZED ARRAY
for i in range(N):
    for j in range(F):
        ar[i][j]=int(input())
print(ar)


回答 17

如果使用numpy,则可以轻松创建2d数组:

import numpy as np

row = 3
col = 5
num = 10
x = np.full((row, col), num)

X

array([[10, 10, 10, 10, 10],
       [10, 10, 10, 10, 10],
       [10, 10, 10, 10, 10]])

If you use numpy, you can easily create 2d arrays:

import numpy as np

row = 3
col = 5
num = 10
x = np.full((row, col), num)

x

array([[10, 10, 10, 10, 10],
       [10, 10, 10, 10, 10],
       [10, 10, 10, 10, 10]])

回答 18

row=5
col=5
[[x]*col for x in [b for b in range(row)]]

以上将为您提供5×5 2D阵列

[[0, 0, 0, 0, 0],
 [1, 1, 1, 1, 1],
 [2, 2, 2, 2, 2],
 [3, 3, 3, 3, 3],
 [4, 4, 4, 4, 4]]

它使用嵌套列表推导。细分如下:

[[x]*col for x in [b for b in range(row)]]

[x] * col->
在-> x中对x 求值的最终表达式将是迭代器提供的值
[b表示range(row)中b的值]]->迭代器。

[b代表b在range(row)中的b]],因为row = 5,
所以其计算结果为[0,1,2,3,4],因此现在简化为

[[x]*col for x in [0,1,2,3,4]]

对于[0,1,2,3,4]中的x,这将计算为[[0] * 5]-> x = 0第一次迭代
[对于[ 0,1,2,3 中的x,[1] * 5, 3,4]]-> x = 1,第2次迭代
[[2] * 5 for x in [0,1,2,3,4]]-> x = 2,第3次迭代
[[3] * 5对于[0,1,2,3,4]中的x – x等于3 =第4次迭代
[[4] * 5对于[0,1,2,3,4]中的x [x] = 4第5次迭代

row=5
col=5
[[x]*col for x in [b for b in range(row)]]

The above will give you a 5×5 2D array

[[0, 0, 0, 0, 0],
 [1, 1, 1, 1, 1],
 [2, 2, 2, 2, 2],
 [3, 3, 3, 3, 3],
 [4, 4, 4, 4, 4]]

It is using nested list comprehension. Breakdown as below:

[[x]*col for x in [b for b in range(row)]]

[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

[[x]*col for x in [0,1,2,3,4]]

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


回答 19

这是我在不使用其他库的情况下教新程序员的最佳方法。我想要更好的东西。

def initialize_twodlist(value):
    list=[]
    for row in range(10):
        list.append([value]*10)
    return list

This is the best I’ve found for teaching new programmers, and without using additional libraries. I’d like something better though.

def initialize_twodlist(value):
    list=[]
    for row in range(10):
        list.append([value]*10)
    return list

回答 20

这是一个更简单的方法:

import numpy as np
twoD = np.array([[]*m]*n)

要使用任何“ x”值初始化所有单元格,请使用:

twoD = np.array([[x]*m]*n

Here is an easier way :

import numpy as np
twoD = np.array([[]*m]*n)

For initializing all cells with any ‘x’ value use :

twoD = np.array([[x]*m]*n

回答 21

我经常使用这种方法来初始化二维数组

n=[[int(x) for x in input().split()] for i in range(int(input())]

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


回答 22

可以从以下系列中得出添加尺寸的一般模式:

x = 0
mat1 = []
for i in range(3):
    mat1.append(x)
    x+=1
print(mat1)


x=0
mat2 = []
for i in range(3):
    tmp = []
    for j in range(4):
        tmp.append(x)
        x+=1
    mat2.append(tmp)

print(mat2)


x=0
mat3 = []
for i in range(3):
    tmp = []
    for j in range(4):
        tmp2 = []
        for k in range(5):
            tmp2.append(x)
            x+=1
        tmp.append(tmp2)
    mat3.append(tmp)

print(mat3)

The general pattern to add dimensions could be drawn from this series:

x = 0
mat1 = []
for i in range(3):
    mat1.append(x)
    x+=1
print(mat1)


x=0
mat2 = []
for i in range(3):
    tmp = []
    for j in range(4):
        tmp.append(x)
        x+=1
    mat2.append(tmp)

print(mat2)


x=0
mat3 = []
for i in range(3):
    tmp = []
    for j in range(4):
        tmp2 = []
        for k in range(5):
            tmp2.append(x)
            x+=1
        tmp.append(tmp2)
    mat3.append(tmp)

print(mat3)

回答 23

您可以尝试使用此[[0] * 10] * 10。这将返回由10行10列组成的二维数组,每个单元格的值为0。

You can try this [[0]*10]*10. This will return the 2d array of 10 rows and 10 columns with value 0 for each cell.


回答 24

lst = [[0] * m对于范围(n)中的i]

初始化所有矩阵n =行和m =列

lst=[[0]*m for i in range(n)]

initialize all matrix n=rows and m=columns


回答 25

另一种方法是使用字典来保存二维数组。

twoD = {}
twoD[0,0] = 0
print(twoD[0,0]) # ===> prints 0

这仅可以保存任何1D,2D值,并将其初始化为0任何其他int值,请使用collections

import collections
twoD = collections.defaultdict(int)
print(twoD[0,0]) # ==> prints 0
twoD[1,1] = 1
print(twoD[1,1]) # ==> prints 1

Another way is to use a dictionary to hold a two-dimensional array.

twoD = {}
twoD[0,0] = 0
print(twoD[0,0]) # ===> prints 0

This just can hold any 1D, 2D values and to initialize this to 0 or any other int value, use collections.

import collections
twoD = collections.defaultdict(int)
print(twoD[0,0]) # ==> prints 0
twoD[1,1] = 1
print(twoD[1,1]) # ==> prints 1

回答 26

码:

num_rows, num_cols = 4, 2
initial_val = 0
matrix = [[initial_val] * num_cols for _ in range(num_rows)]
print(matrix) 
# [[0, 0], [0, 0], [0, 0], [0, 0]]

initial_val 必须是不变的。

Code:

num_rows, num_cols = 4, 2
initial_val = 0
matrix = [[initial_val] * num_cols for _ in range(num_rows)]
print(matrix) 
# [[0, 0], [0, 0], [0, 0], [0, 0]]

initial_val must be immutable.


回答 27

from random import randint
l = []

for i in range(10):
    k=[]
    for j in range(10):
        a= randint(1,100)
        k.append(a)

    l.append(k)




print(l)
print(max(l[2]))

b = []
for i in range(10):
    a = l[i][5]
    b.append(a)

print(min(b))
from random import randint
l = []

for i in range(10):
    k=[]
    for j in range(10):
        a= randint(1,100)
        k.append(a)

    l.append(k)




print(l)
print(max(l[2]))

b = []
for i in range(10):
    a = l[i][5]
    b.append(a)

print(min(b))