如何在Python中声明数组?

时间:2021-08-11 21:29:17

How do I declare an array in Python?

如何在Python中声明数组?

I can't find any reference to arrays in the documentation.

我在文档中找不到任何对数组的引用。

16 个解决方案

#1


277  

variable = []

Now variable refers to an empty list*.

现在变量指的是一个空列表*。

Of course this is an assignment, not a declaration. There's no way to say in Python "this variable should never refer to anything other than a list", since Python is dynamically typed.

当然这是作业,不是声明。由于Python是动态类型的,所以在Python中没有办法说“这个变量应该永远引用列表之外的内容”。


*The default built-in Python type is called a list, not an array. It is an ordered container of arbitrary length that can hold a heterogenous collection of objects (their types do not matter and can be freely mixed). This should not be confused with the array module, which offers a type closer to the C array type; the contents must be homogenous (all of the same type), but the length is still dynamic.

*默认的内置Python类型被称为列表,而不是数组。它是一个任意长度的有序容器,可以容纳一个异构的对象集合(它们的类型不重要,可以*混合)。这不应该与数组模块混淆,后者提供更接近C数组类型的类型;内容必须是同质的(所有类型相同),但是长度仍然是动态的。

#2


94  

You don't actually declare things, but this is how you create an array in Python:

实际上你并没有声明东西,但这是你在Python中创建数组的方式:

from array import array
intarray = array('i')

For more info see the array module: http://docs.python.org/library/array.html

有关更多信息,请参见数组模块:http://docs.python.org/library/array.html。

Now possible you don't want an array, but a list, but others have answered that already. :)

现在你可能不想要一个数组,而是一个列表,但是其他人已经回答了这个问题。:)

#3


57  

I think you (meant)want an list with the first 30 cells already filled. So

我认为你想要一个包含前30个单元格的列表。所以

   f = []

   for i in range(30):
       f.append(0)

An example to where this could be used is in Fibonacci sequence. See problem 2 in Project Euler

斐波那契数列中有一个例子可以说明这一点。参见欧拉项目中的问题2

#4


56  

This is surprisingly complex topic in Python.

这在Python中是一个非常复杂的主题。

Practical answer

Arrays are represented by class list (see reference and do not mix them with generators).

数组由类列表表示(请参阅引用,不要与生成器混合)。

Check out usage examples:

查看使用例子:

# empty array
arr = [] 

# init with values (can contain mixed types)
arr = [1, "eels"]

# get item by index (can be negative to access end of array)
arr = [1, 2, 3, 4, 5, 6]
arr[0]  # 1
arr[-1] # 6

# get length
length = len(arr)

# supports append and insert
arr.append(8)
arr.insert(6, 7)

Theoretical answer

Under the hood Python's list is a wrapper for a real array which contains references to items. Also, underlying array is created with some extra space.

在hood Python的列表中,是一个包含对项目的引用的真实数组的包装器。此外,底层数组是用一些额外的空间创建的。

Consequences of this are:

的后果是:

  • random access is really cheap (arr[6653] is same to arr[0])
  • 随机访问真的很便宜(arr[6653]与arr[0]相同)
  • append operation is 'for free' while some extra space
  • append操作是“免费”的,同时还有一些额外的空间。
  • insert operation is expensive
  • 插入操作是昂贵的

Check this awesome table of operations complexity.

检查这个令人敬畏的操作复杂性表。

Also, please see this picture, where I've tried to show most important differences between array, array of references and linked list: 如何在Python中声明数组?

另外,请看这张照片,在这里我试图展示数组、引用数组和链表之间最重要的区别:

#5


35  

This is how:

这就是:

my_array = [1, 'rebecca', 'allard', 15]

#6


16  

You don't declare anything in Python. You just use it. I recommend you start out with something like http://diveintopython.net.

您没有在Python中声明任何内容。你只是使用它。我建议您从http://diveintopython.net开始。

#7


13  

for calculations, use numpy arrays like this:

对于计算,使用象这样的numpy数组:

import numpy as np

a = np.ones((3,2))        # a 2D array with 3 rows, 2 columns, filled with ones
b = np.array([1,2,3])     # a 1D array initialised using a list [1,2,3]
c = np.linspace(2,3,100)  # an array with 100 points beteen (and including) 2 and 3

print(a*1.5)  # all elements of a times 1.5
print(a.T+b)  # b added to the transpose of a

these numpy arrays can be saved and loaded from disk (even compressed) and complex calculations with large amounts of elements is C-like fast. Much used in scientific environments. See here for more...

这些numpy数组可以从磁盘(甚至是压缩的)中保存和加载,使用大量元素的复杂计算速度非常快。在科学环境中被广泛使用。在这里看到更多…

#8


11  

I would normally just do a = [1,2,3] which is actually a list but for arrays look at this formal definition

我通常只需要做a =[1,2,3]这实际上是一个列表,但是对于数组来说,要看这个正式的定义

#9


11  

A couple of contributions suggested that arrays in python are represented by lists. Perhaps theoretically/under the hood that is correct however a major distinction between the two is the fact that lists accept mixed data types and mixed numeric types, on the other hand array requires a type-code restricting all elements to the determined type:

一些贡献表明,python中的数组由列表表示。也许在理论上/在表面上是正确的,但是两者之间的一个主要区别是列表接受混合数据类型和混合数字类型,另一方面,数组需要一个类型代码,将所有元素限制为确定的类型:

list_01 = [4, 6.2, 7-2j, 'flo', 'cro']

list_01
Out[85]: [4, 6.2, (7-2j), 'flo', 'cro']

This is not possible using array().

使用array()是不可能的。

#10


9  

To add to Lennart's answer, an array may be created like this:

为了补充Lennart的答案,可以创建这样的数组:

from array import array
float_array = array("f",values)

where values can take the form of a tuple, list, or np.array, but not array:

其中的值可以采用元组、列表或np的形式。数组,而不是数组:

values = [1,2,3]
values = (1,2,3)
values = np.array([1,2,3],'f')
# 'i' will work here too, but if array is 'i' then values have to be int
wrong_values = array('f',[1,2,3])
# TypeError: 'array.array' object is not callable

and the output will still be the same:

输出仍然是一样的:

print(float_array)
print(float_array[1])
print(isinstance(float_array[1],float))

# array('f', [1.0, 2.0, 3.0])
# 2.0
# True

Most methods for list work with array as well, common ones being pop(), extend(), and append().

列表的大多数方法也使用数组,常见的方法有pop()、extend()和append()。

Judging from the answers and comments, it appears that the array data structure isn't that popular. I like it though, the same way as one might prefer a tuple over a list.

从答案和评论来看,数组数据结构似乎不是那么流行。我喜欢它,就像人们喜欢tuple而不喜欢list一样。

The array structure has stricter rules than a list or np.array, and this can reduce errors and make debugging easier, especially when working with numerical data.

数组结构具有比列表或np更严格的规则。这可以减少错误,使调试更加容易,特别是在处理数值数据时。

Attempts to insert/append a float to an int array will throw a TypeError:

尝试插入/附加一个浮点数到int数组将抛出一个类型错误:

values = [1,2,3]
int_array = array("i",values)
int_array.append(float(1))
# or int_array.extend([float(1)])

# TypeError: integer argument expected, got float

Keeping values which are meant to be integers (e.g. list of indices) in the array form may therefore prevent a "TypeError: list indices must be integers, not float", since arrays can be iterated over, similar to np.array and lists:

保持数组形式中的值为整数(例如索引列表)可以避免“类型错误:列表索引必须是整数,而不是浮点数”,因为数组可以迭代,类似于np。数组和列表:

int_array = array('i',[1,2,3])
data = [11,22,33,44,55]
sample = []
for i in int_array:
    sample.append(data[i])

Annoyingly, appending an int to a float array will cause the int to become a float, without throwing an exception.

令人恼火的是,在浮点数组中附加int将导致int变成浮点数,而不会引发异常。

np.array retain the same data type for its entries too, but instead of giving an error it will change its data type to fit new entries (usually to double or str):

np。数组也为其条目保留相同的数据类型,但它将更改其数据类型以适应新条目(通常为double或str):

import numpy as np
numpy_int_array = np.array([1,2,3],'i')
for i in numpy_int_array:
    print(type(i))
    # <class 'numpy.int32'>
numpy_int_array_2 = np.append(numpy_int_array,int(1))
# still <class 'numpy.int32'>
numpy_float_array = np.append(numpy_int_array,float(1))
# <class 'numpy.float64'> for all values
numpy_str_array = np.append(numpy_int_array,"1")
# <class 'numpy.str_'> for all values
data = [11,22,33,44,55]
sample = []
for i in numpy_int_array_2:
    sample.append(data[i])
    # no problem here, but TypeError for the other two

This is true during assignment as well. If the data type is specified, np.array will, wherever possible, transform the entries to that data type:

这在作业中也是正确的。如果指定了数据类型,则为np。数组将尽可能将条目转换为该数据类型:

int_numpy_array = np.array([1,2,float(3)],'i')
# 3 becomes an int
int_numpy_array_2 = np.array([1,2,3.9],'i')
# 3.9 gets truncated to 3 (same as int(3.9))
invalid_array = np.array([1,2,"string"],'i')
# ValueError: invalid literal for int() with base 10: 'string'
# Same error as int('string')
str_numpy_array = np.array([1,2,3],'str')
print(str_numpy_array)
print([type(i) for i in str_numpy_array])
# ['1' '2' '3']
# <class 'numpy.str_'>

or, in essence:

或者,从本质上讲:

data = [1.2,3.4,5.6]
list_1 = np.array(data,'i').tolist()
list_2 = [int(i) for i in data]
print(list_1 == list_2)
# True

while array will simply give:

而数组将简单地给出:

invalid_array = array([1,2,3.9],'i')
# TypeError: integer argument expected, got float

Because of this, it is not a good idea to use np.array for type-specific commands. The array structure is useful here. list preserves the data type of the values.

因此,使用np并不是一个好主意。数组为特定类型的命令。数组结构在这里很有用。列表保存值的数据类型。

And for something I find rather pesky: the data type is specified as the first argument in array(), but (usually) the second in np.array(). :|

我发现有些麻烦:数据类型被指定为数组()中的第一个参数,但(通常)是np.array()中的第二个参数。:|

The relation to C is referred to here: Python List vs. Array - when to use?

这里引用了与C的关系:Python列表与数组——什么时候使用?

Have fun exploring!

祝您玩得愉快!

Note: The typed and rather strict nature of array leans more towards C rather than Python, and by design Python does not have many type-specific constraints in its functions. Its unpopularity also creates a positive feedback in collaborative work, and replacing it mostly involves an additional [int(x) for x in file]. It is therefore entirely viable and reasonable to ignore the existence of array. It shouldn't hinder most of us in any way. :D

注意:数组的类型和相当严格的性质倾向于C而不是Python,而设计Python在其函数中没有很多类型特定的约束。它的不受欢迎也在协作工作中产生了积极的反馈,替换它主要涉及到文件中x的额外的[int(x)]。因此,忽略数组的存在是完全可行和合理的。它不应该以任何方式阻碍我们大多数人。:D

#11


6  

Following on from Lennart, there's also numpy which implements homogeneous multi-dimensional arrays.

继Lennart之后,也有了实现同质多维数组的numpy。

#12


5  

Python calls them lists. You can write a list literal with square brackets and commas:

Python称之为列表。你可以用方括号和逗号写一个列表:

>>> [6,28,496,8128]
[6, 28, 496, 8128]

#13


5  

How about this...

这个怎么样…

>>> a = range(12)
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
>>> a[7]
6

#14


2  

I had an array of strings and needed an array of the same length of booleans initiated to True. This is what I did

我有一个字符串数组,需要一个布尔值为True的数组。这就是我所做的。

strs = ["Hi","Bye"] 
bools = [ True for s in strs ]

#15


1  

JohnMachin's comment should be the real answer. All the other answers are just workarounds in my opinion! So:

JohnMachin的评论应该是真正的答案。在我看来,所有其他的答案都只是个变通办法。所以:

array=[0]*element_count

#16


1  

You can create lists and convert them into arrays or you can create array using numpy module. Below are few examples to illustrate the same. Numpy also makes it easier to work with multi-dimensional arrays.

可以创建列表并将它们转换为数组,也可以使用numpy模块创建数组。下面是几个例子来说明这一点。Numpy还使使用多维数组变得更容易。

import numpy as np
a = np.array([1, 2, 3, 4])

#For custom inputs
a = np.array([int(x) for x in input().split()])

You can also reshape this array into a 2X2 matrix using reshape function which takes in input as the dimensions of the matrix.

您还可以使用将输入作为矩阵的维数的重塑函数将这个数组重塑为一个2X2矩阵。

mat = a.reshape(2, 2)

#1


277  

variable = []

Now variable refers to an empty list*.

现在变量指的是一个空列表*。

Of course this is an assignment, not a declaration. There's no way to say in Python "this variable should never refer to anything other than a list", since Python is dynamically typed.

当然这是作业,不是声明。由于Python是动态类型的,所以在Python中没有办法说“这个变量应该永远引用列表之外的内容”。


*The default built-in Python type is called a list, not an array. It is an ordered container of arbitrary length that can hold a heterogenous collection of objects (their types do not matter and can be freely mixed). This should not be confused with the array module, which offers a type closer to the C array type; the contents must be homogenous (all of the same type), but the length is still dynamic.

*默认的内置Python类型被称为列表,而不是数组。它是一个任意长度的有序容器,可以容纳一个异构的对象集合(它们的类型不重要,可以*混合)。这不应该与数组模块混淆,后者提供更接近C数组类型的类型;内容必须是同质的(所有类型相同),但是长度仍然是动态的。

#2


94  

You don't actually declare things, but this is how you create an array in Python:

实际上你并没有声明东西,但这是你在Python中创建数组的方式:

from array import array
intarray = array('i')

For more info see the array module: http://docs.python.org/library/array.html

有关更多信息,请参见数组模块:http://docs.python.org/library/array.html。

Now possible you don't want an array, but a list, but others have answered that already. :)

现在你可能不想要一个数组,而是一个列表,但是其他人已经回答了这个问题。:)

#3


57  

I think you (meant)want an list with the first 30 cells already filled. So

我认为你想要一个包含前30个单元格的列表。所以

   f = []

   for i in range(30):
       f.append(0)

An example to where this could be used is in Fibonacci sequence. See problem 2 in Project Euler

斐波那契数列中有一个例子可以说明这一点。参见欧拉项目中的问题2

#4


56  

This is surprisingly complex topic in Python.

这在Python中是一个非常复杂的主题。

Practical answer

Arrays are represented by class list (see reference and do not mix them with generators).

数组由类列表表示(请参阅引用,不要与生成器混合)。

Check out usage examples:

查看使用例子:

# empty array
arr = [] 

# init with values (can contain mixed types)
arr = [1, "eels"]

# get item by index (can be negative to access end of array)
arr = [1, 2, 3, 4, 5, 6]
arr[0]  # 1
arr[-1] # 6

# get length
length = len(arr)

# supports append and insert
arr.append(8)
arr.insert(6, 7)

Theoretical answer

Under the hood Python's list is a wrapper for a real array which contains references to items. Also, underlying array is created with some extra space.

在hood Python的列表中,是一个包含对项目的引用的真实数组的包装器。此外,底层数组是用一些额外的空间创建的。

Consequences of this are:

的后果是:

  • random access is really cheap (arr[6653] is same to arr[0])
  • 随机访问真的很便宜(arr[6653]与arr[0]相同)
  • append operation is 'for free' while some extra space
  • append操作是“免费”的,同时还有一些额外的空间。
  • insert operation is expensive
  • 插入操作是昂贵的

Check this awesome table of operations complexity.

检查这个令人敬畏的操作复杂性表。

Also, please see this picture, where I've tried to show most important differences between array, array of references and linked list: 如何在Python中声明数组?

另外,请看这张照片,在这里我试图展示数组、引用数组和链表之间最重要的区别:

#5


35  

This is how:

这就是:

my_array = [1, 'rebecca', 'allard', 15]

#6


16  

You don't declare anything in Python. You just use it. I recommend you start out with something like http://diveintopython.net.

您没有在Python中声明任何内容。你只是使用它。我建议您从http://diveintopython.net开始。

#7


13  

for calculations, use numpy arrays like this:

对于计算,使用象这样的numpy数组:

import numpy as np

a = np.ones((3,2))        # a 2D array with 3 rows, 2 columns, filled with ones
b = np.array([1,2,3])     # a 1D array initialised using a list [1,2,3]
c = np.linspace(2,3,100)  # an array with 100 points beteen (and including) 2 and 3

print(a*1.5)  # all elements of a times 1.5
print(a.T+b)  # b added to the transpose of a

these numpy arrays can be saved and loaded from disk (even compressed) and complex calculations with large amounts of elements is C-like fast. Much used in scientific environments. See here for more...

这些numpy数组可以从磁盘(甚至是压缩的)中保存和加载,使用大量元素的复杂计算速度非常快。在科学环境中被广泛使用。在这里看到更多…

#8


11  

I would normally just do a = [1,2,3] which is actually a list but for arrays look at this formal definition

我通常只需要做a =[1,2,3]这实际上是一个列表,但是对于数组来说,要看这个正式的定义

#9


11  

A couple of contributions suggested that arrays in python are represented by lists. Perhaps theoretically/under the hood that is correct however a major distinction between the two is the fact that lists accept mixed data types and mixed numeric types, on the other hand array requires a type-code restricting all elements to the determined type:

一些贡献表明,python中的数组由列表表示。也许在理论上/在表面上是正确的,但是两者之间的一个主要区别是列表接受混合数据类型和混合数字类型,另一方面,数组需要一个类型代码,将所有元素限制为确定的类型:

list_01 = [4, 6.2, 7-2j, 'flo', 'cro']

list_01
Out[85]: [4, 6.2, (7-2j), 'flo', 'cro']

This is not possible using array().

使用array()是不可能的。

#10


9  

To add to Lennart's answer, an array may be created like this:

为了补充Lennart的答案,可以创建这样的数组:

from array import array
float_array = array("f",values)

where values can take the form of a tuple, list, or np.array, but not array:

其中的值可以采用元组、列表或np的形式。数组,而不是数组:

values = [1,2,3]
values = (1,2,3)
values = np.array([1,2,3],'f')
# 'i' will work here too, but if array is 'i' then values have to be int
wrong_values = array('f',[1,2,3])
# TypeError: 'array.array' object is not callable

and the output will still be the same:

输出仍然是一样的:

print(float_array)
print(float_array[1])
print(isinstance(float_array[1],float))

# array('f', [1.0, 2.0, 3.0])
# 2.0
# True

Most methods for list work with array as well, common ones being pop(), extend(), and append().

列表的大多数方法也使用数组,常见的方法有pop()、extend()和append()。

Judging from the answers and comments, it appears that the array data structure isn't that popular. I like it though, the same way as one might prefer a tuple over a list.

从答案和评论来看,数组数据结构似乎不是那么流行。我喜欢它,就像人们喜欢tuple而不喜欢list一样。

The array structure has stricter rules than a list or np.array, and this can reduce errors and make debugging easier, especially when working with numerical data.

数组结构具有比列表或np更严格的规则。这可以减少错误,使调试更加容易,特别是在处理数值数据时。

Attempts to insert/append a float to an int array will throw a TypeError:

尝试插入/附加一个浮点数到int数组将抛出一个类型错误:

values = [1,2,3]
int_array = array("i",values)
int_array.append(float(1))
# or int_array.extend([float(1)])

# TypeError: integer argument expected, got float

Keeping values which are meant to be integers (e.g. list of indices) in the array form may therefore prevent a "TypeError: list indices must be integers, not float", since arrays can be iterated over, similar to np.array and lists:

保持数组形式中的值为整数(例如索引列表)可以避免“类型错误:列表索引必须是整数,而不是浮点数”,因为数组可以迭代,类似于np。数组和列表:

int_array = array('i',[1,2,3])
data = [11,22,33,44,55]
sample = []
for i in int_array:
    sample.append(data[i])

Annoyingly, appending an int to a float array will cause the int to become a float, without throwing an exception.

令人恼火的是,在浮点数组中附加int将导致int变成浮点数,而不会引发异常。

np.array retain the same data type for its entries too, but instead of giving an error it will change its data type to fit new entries (usually to double or str):

np。数组也为其条目保留相同的数据类型,但它将更改其数据类型以适应新条目(通常为double或str):

import numpy as np
numpy_int_array = np.array([1,2,3],'i')
for i in numpy_int_array:
    print(type(i))
    # <class 'numpy.int32'>
numpy_int_array_2 = np.append(numpy_int_array,int(1))
# still <class 'numpy.int32'>
numpy_float_array = np.append(numpy_int_array,float(1))
# <class 'numpy.float64'> for all values
numpy_str_array = np.append(numpy_int_array,"1")
# <class 'numpy.str_'> for all values
data = [11,22,33,44,55]
sample = []
for i in numpy_int_array_2:
    sample.append(data[i])
    # no problem here, but TypeError for the other two

This is true during assignment as well. If the data type is specified, np.array will, wherever possible, transform the entries to that data type:

这在作业中也是正确的。如果指定了数据类型,则为np。数组将尽可能将条目转换为该数据类型:

int_numpy_array = np.array([1,2,float(3)],'i')
# 3 becomes an int
int_numpy_array_2 = np.array([1,2,3.9],'i')
# 3.9 gets truncated to 3 (same as int(3.9))
invalid_array = np.array([1,2,"string"],'i')
# ValueError: invalid literal for int() with base 10: 'string'
# Same error as int('string')
str_numpy_array = np.array([1,2,3],'str')
print(str_numpy_array)
print([type(i) for i in str_numpy_array])
# ['1' '2' '3']
# <class 'numpy.str_'>

or, in essence:

或者,从本质上讲:

data = [1.2,3.4,5.6]
list_1 = np.array(data,'i').tolist()
list_2 = [int(i) for i in data]
print(list_1 == list_2)
# True

while array will simply give:

而数组将简单地给出:

invalid_array = array([1,2,3.9],'i')
# TypeError: integer argument expected, got float

Because of this, it is not a good idea to use np.array for type-specific commands. The array structure is useful here. list preserves the data type of the values.

因此,使用np并不是一个好主意。数组为特定类型的命令。数组结构在这里很有用。列表保存值的数据类型。

And for something I find rather pesky: the data type is specified as the first argument in array(), but (usually) the second in np.array(). :|

我发现有些麻烦:数据类型被指定为数组()中的第一个参数,但(通常)是np.array()中的第二个参数。:|

The relation to C is referred to here: Python List vs. Array - when to use?

这里引用了与C的关系:Python列表与数组——什么时候使用?

Have fun exploring!

祝您玩得愉快!

Note: The typed and rather strict nature of array leans more towards C rather than Python, and by design Python does not have many type-specific constraints in its functions. Its unpopularity also creates a positive feedback in collaborative work, and replacing it mostly involves an additional [int(x) for x in file]. It is therefore entirely viable and reasonable to ignore the existence of array. It shouldn't hinder most of us in any way. :D

注意:数组的类型和相当严格的性质倾向于C而不是Python,而设计Python在其函数中没有很多类型特定的约束。它的不受欢迎也在协作工作中产生了积极的反馈,替换它主要涉及到文件中x的额外的[int(x)]。因此,忽略数组的存在是完全可行和合理的。它不应该以任何方式阻碍我们大多数人。:D

#11


6  

Following on from Lennart, there's also numpy which implements homogeneous multi-dimensional arrays.

继Lennart之后,也有了实现同质多维数组的numpy。

#12


5  

Python calls them lists. You can write a list literal with square brackets and commas:

Python称之为列表。你可以用方括号和逗号写一个列表:

>>> [6,28,496,8128]
[6, 28, 496, 8128]

#13


5  

How about this...

这个怎么样…

>>> a = range(12)
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
>>> a[7]
6

#14


2  

I had an array of strings and needed an array of the same length of booleans initiated to True. This is what I did

我有一个字符串数组,需要一个布尔值为True的数组。这就是我所做的。

strs = ["Hi","Bye"] 
bools = [ True for s in strs ]

#15


1  

JohnMachin's comment should be the real answer. All the other answers are just workarounds in my opinion! So:

JohnMachin的评论应该是真正的答案。在我看来,所有其他的答案都只是个变通办法。所以:

array=[0]*element_count

#16


1  

You can create lists and convert them into arrays or you can create array using numpy module. Below are few examples to illustrate the same. Numpy also makes it easier to work with multi-dimensional arrays.

可以创建列表并将它们转换为数组,也可以使用numpy模块创建数组。下面是几个例子来说明这一点。Numpy还使使用多维数组变得更容易。

import numpy as np
a = np.array([1, 2, 3, 4])

#For custom inputs
a = np.array([int(x) for x in input().split()])

You can also reshape this array into a 2X2 matrix using reshape function which takes in input as the dimensions of the matrix.

您还可以使用将输入作为矩阵的维数的重塑函数将这个数组重塑为一个2X2矩阵。

mat = a.reshape(2, 2)