python創建與遍歷List二維列表


python創建與遍歷List二維列表

覺得有用的話,歡迎一起討論相互學習~

我的微博我的github我的B站

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM