Python中的多维列表
Python中的列表可以有不止一个额外的维度。请记住,一个列表可以包含其他列表,这个基本原则可以一遍又一遍地应用。多维列表是列表中的列表。通常,字典比Python中的多维列表是更好的选择。
访问多维列表:
方法一:
# Python program to demonstrate printing
# of complete multidimensional list
a = [[2, 4, 6, 8, 10], [3, 6, 9, 12, 15], [4, 8, 12, 16, 20]]
print(a)
输出:
[[2, 4, 6, 8, 10], [3, 6, 9, 12, 15], [4, 8, 12, 16, 20]]
方法2:在循环的帮助下访问。
# Python program to demonstrate printing
# of complete multidimensional list row
# by row.
a = [[2, 4, 6, 8, 10], [3, 6, 9, 12, 15], [4, 8, 12, 16, 20]]
for record in a:
print(record)
输出:
[2, 4, 6, 8, 10]
[3, 6, 9, 12, 15]
[4, 8, 12, 16, 20]
方法 3:使用方括号访问。
例子:
# Python program to demonstrate that we
# can access multidimensional list using
# square brackets
a = [ [2, 4, 6, 8 ],
[ 1, 3, 5, 7 ],
[ 8, 6, 4, 2 ],
[ 7, 5, 3, 1 ] ]
for i in range(len(a)) :
for j in range(len(a[i])) :
print(a[i][j], end=" ")
print()
输出:
2 4 6 8
1 3 5 7
8 6 4 2
7 5 3 1
创建一个全为零的多维列表:
# Python program to create a m x n matrix
# with all 0s
m = 4
n = 5
a = [[0 for x in range(n)] for x in range(m)]
print(a)
输出:
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
多维列表上的方法
1. append():在列表末尾添加一个元素。
例子:
# Adding a sublist
a = [[2, 4, 6, 8, 10], [3, 6, 9, 12, 15], [4, 8, 12, 16, 20]]
a.append([5, 10, 15, 20, 25])
print(a)
输出:
[[2, 4, 6, 8, 10], [3, 6, 9, 12, 15], [4, 8, 12, 16, 20], [5, 10, 15, 20, 25]]
2. extend():将列表(或任何可迭代)的元素添加到当前列表的末尾。
# Extending a sublist
a = [[2, 4, 6, 8, 10], [3, 6, 9, 12, 15], [4, 8, 12, 16, 20]]
a[0].extend([12, 14, 16, 18])
print(a)
输出:
[[2, 4, 6, 8, 10, 12, 14, 16, 18], [3, 6, 9, 12, 15], [4, 8, 12, 16, 20]]
3. reverse():反转列表的顺序。
# Reversing a sublist
a = [[2, 4, 6, 8, 10], [3, 6, 9, 12, 15], [4, 8, 12, 16, 20]]
a[2].reverse()
print(a)
输出:
[[2, 4, 6, 8, 10], [3, 6, 9, 12, 15], [20, 16, 12, 8, 4]]