Python中的二维列表使用及说明
目录
- 一、概念
- 二、创建二维列表
- 1、追加一维列标来生成二维列标
- 2、直接赋值生成二维列表
- 三、一维列标与二维列表的转换
- 1、一维列表转换成二维列表
- 2、二维列表转换成一维列表
- 3、利用NumPy实现数组的变维操作
- 四、访问二维列表
- 1、访问行
- 2、访问元素
- 3、NumPy二维数组的访问
- 总结
一、概念
二维列表的元素还是列表(列表的嵌套),称之为二维列表。
需要通过行标和列标来访问二维列表的元素
二、创建二维列表
1、追加一维列标来生成二维列标
生成一个4行3列的二维列表
row1 = [3, 4, 5] row2 = [1, 5, 9] row3 = [2, 5, 8] row4 = [7, 8, 9] matrix = [] matrix.append(row1) matrix.append(row2) matrix.append(row3) matrix.append(row4) print(matrix)
输出结果:
[[3, 4, 5], [1, 5, 9], [2, 5, 8], [7, 8, 9]]
2、直接赋值生成二维列表
定义一个3行4列的二维列表
matrix = [[], [], []] matrix[0] = [3, 4, 5, 6] matrix[1] = [8, 7, 9, 5] matrix[2] = [0, 2, 5, 8] print(matrix)
输出结果:
[[3, 4, 5, 6], [8, 7, 9, 5], [0, 2, 5, 8]]
三、一维列标与二维列表的转换
1、一维列表转换成二维列表
将1到24的全部数字按顺序放到一个4行6列的二维列表里
# 将1到24的全部数字按顺序放到一个4行6列的二维列表里 nums = [] for i in range(1, 25): nums.append(i) martix = [] for k in range(4): row = [] for j in range(1, 7): row.append(j + 6 * k) martix.append(row) for arr in martix: print(arr)
输出结果:
[1, 2, 3, 4, 5, 6]
[7, 8, 9, 10, 11, 12]
[13, 14, 15, 16, 17, 18]
[19, 20, 21, 22, 23, 24]
2、二维列表转换成一维列表
将一个3行5列的二维列表扁平化一维列表
# 将一个3行5列的二维列表扁平化一维列表 nums = [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15]] arr = [] for i in nums: for j in i: arr.append(j) print(arr)
输出结果:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
3、利用NumPy实现数组的变维操作
利用NumPy数组提供的 reshape(m, n) 实现数组的变维
(1)一维数组变成二维数组
In [31]:import numpy as np In [32]:arr1 = np.arange(1,25) # arange() 创建一个等差数组 In [33]:arr2 = arr1.reshape(4, 6) # reshape()一维转二维 In [34]:arr2 Out[34]: array([[ 1, 2, 3, 4, 5, 6], [ 7, 8, 9, 10, 11, 12], [13, 14, 15, 16, 17, 18], [19, 20, 21, 22, 23, 24]]) In [35]:arr2 = arr1.reshape(3, 8) In [36]:arr2 Out[36]: array([[ 1, 2, 3, 4, 5, 6, 7, 8], [ 9, 10, 11, 12, 13, 14, 15, 16], [17, 18, 19, 20, 21, 22, 23, 24]])
(2)二维数组转换成一维数组
In [36]:arr2 Out[36]: array([[ 1, 2, 3, 4, 5, 6, 7, 8], [ 9, 10, 11, 12, 13, 14, 15, 16], [17, 18, 19, 20, 21, 22, 23, 24]]) In [37]:arr1 = arr2.reshape(1, 24)[0] In [38]:arr1 Out[38]: array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24])
四、访问二维列表
通过行标与列标来访问二维列表(可以通过切片运算访问行)
1、访问行
In [36]:arr2 Out[36]: array([[ 1, 2, 3, 4, 5, 6, 7, 8], [ 9, 10, 11, 12, 13, 14, 15, 16], [17, 18, 19, 20, 21, 22, 23, 24]]) In [39]:arr2[1] Out[39]: array([ 9, 10, 11, 12, 13, 14, 15, 16])
2、访问元素
In [40]:arr2 Out[40]: array([[ 1, 2, 3, 4, 5, 6, 7, 8], [ 9, 10, 11, 12, 13, 14, 15, 16], [17, 18, 19, 20, 21, 22, 23, 24]]) In [41]:arr2[1][2] # 第2行第3列 Out[41]: 11
3、NumPy二维数组的访问
In [42]:import numpy as np In [43]:arr2 Out[43]: array([[ 1, 2, 3, 4, 5, 6, 7, 8], [ 9, 10, 11, 12, 13, 14, 15, 16], [17, 18, 19, 20, 21, 22, 23, 24]]) In [44]:arr2[1] # 访问行 Out[44]: array([ 9, 10, 11, 12, 13, 14, 15, 16]) In [45]:arr2[:, 0] # 访问列 Out[45]: array([ 1, 9, 17]) In [46]:arr2[2, 3] # 访问元素 Out[46]: 20
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持我们。
赞 (0)