Python creates and traverses a two-dimensional list of List

Python creates List two-dimensional 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]]

Use the two-dimensional list index to traverse the two-dimensional list

Note that the two-dimensional list in python is the same as matlab and C and JAVA, and the number of columns in each row does not need to be equal

'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:778463939
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
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

Use the two-dimensional list handle to traverse the two-dimensional list

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

Guess you like

Origin blog.csdn.net/qdPython/article/details/112966201