python創建與遍歷List二維列表
覺得有用的話,歡迎一起討論相互學習~




python 創建List二維列表
lists = [[] for i in range(3)] # 創建的是多行三列的二維列表
for i in range(3):
lists[0].append(i)
for i in range(5):
lists[1].append(i)
for i in range(7):
lists[2].append(i)
print("lists is:", lists)
# lists is: [[0, 1, 2], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4, 5, 6]]
使用二維列表索引遍歷二維列表
- 注意python中二維列表和matlab以及C和JAVA中一樣,不需要每行中列的數量相等
sum_0 = 0
for i in range(len(lists)):
for j in range(len(lists[i])):
print(lists[i][j])
sum_0 += lists[i][j]
print("The sum_0 of Lists:", sum_0)
# 0
# 1
# 2
# 0
# 1
# 2
# 3
# 4
# 0
# 1
# 2
# 3
# 4
# 5
# 6
# The sum of Lists: 34
使用二維列表句柄遍歷二維列表
sum_1 = 0
for i in lists:
for j in i:
sum_1 += j
print("The sum_1 of Lists:", sum_1)
# The sum_1 of Lists: 34