Python 官方文档:入门教程 => 点击学习
目录一、概念二、创建二维列表1、追加一维列标来生成二维列标2、直接赋值生成二维列表三、一维列标与二维列表的转换1、一维列表转换成二维列表2、二维列表转换成一维列表3、利用NumPy实
二维列表的元素还是列表(列表的嵌套),称之为二维列表。
需要通过行标和列标来访问二维列表的元素
生成一个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]]
定义一个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到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]
将一个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]
利用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])
通过行标与列标来访问二维列表(可以通过切片运算访问行)
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])
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
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
以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。
--结束END--
本文标题: Python中的二维列表使用及说明
本文链接: https://lsjlt.com/news/175369.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
2024-03-01
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0