我们在编写python代码时,直接用乘号创建二维数组,这样直接省力,但赋值后可能会得到错误的结果。为了方便演示,以下代码直接在python环境中编写。
1.声明一个二维数组,用乘号快速复制
C:\Users\***>python
Python 3.9.12 (main, Apr 4 2022, 05:22:27) [MSC v.1916 64 bit (AMD64)] :: Anaconda, Inc. on win32
Warning:
This Python interpreter is in a conda environment, but the environment has
not been activated. Libraries may fail to load. To activate this environment
please see https://conda.io/activation
Type "help", "copyright", "credits" or "license" for more information.
>>> s = [[1] * 3] * 2
2.而得到的二位数组如果用下标赋值则会出现错误
>>> s = [[1] * 3] * 2
>>> s[0][0]=2
>>> s
[[2, 1, 1], [2, 1, 1]]
>>>
当然,如果想快速得到赋值正常的二位数组使用嵌套列表方式进行,如下:
>>> s = [[1] * 3] * 2
>>> s[0][0]=2
>>> s
[[2, 1, 1], [2, 1, 1]]
>>> s = [[1 for _ in range(3)] for _ in range(2)]
>>> s
[[1, 1, 1], [1, 1, 1]]
>>> s[0][0] = 2
>>> s
[[2, 1, 1], [1, 1, 1]]
>>>
tips:
Python中也可以使用NumPy库创建二维数组,而且其具有更高的性能和多样的功能,关注博主,之后详解。
希望本文对你理解如何在Python中新建二维数组并赋值有所帮助!点个免费的赞吧!