Python-- two-dimensional array traversal operation

 

First, through the array (operation Value)

1. Using two-dimensional list traverse the two-dimensional array

List python create 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]]

 Output array of rows and columns

# 输出数组的行和列数
arr = [[1,4,7,10,15], [2,5,8,12,19], [3,6,9,16,22], [10,13,14,17,24]]
print arr.shape  # (4, 5)
# 只输出行数
print arr.shape[0] # 4
# 只输出列数
print arr.shape[1] # 5

or:

In [48]: arr = [[1,4,7,10,15], [2,5,8,12,19], [3,6,9,16,22], [10,13,14,17,24]]

In [49]: len(arr)  #行数
Out[49]: 4

In [50]: len(arr[0]) #列数
Out[50]: 5

 


Indexing through the use of two-dimensional list of two-dimensional list

  • Note that in the two-dimensional list python and matlab as well as in JAVA and C, does not require an equal number of columns per row

 

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 two-dimensional list traversal handles 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

 

2. Using two-dimensional list index (similar to C ++)

 Note: Be sure each two-dimensional list ranks the same number, otherwise it will error. Because Python allows several different two-dimensional array of columns

import numpy as np
world=np.zero([5,5])
for i in range(0,world.shape[0])
    for j in range(0,world.shape[1])
        print (world[i][j])

3. Use the handle to the list

list2d = [[1,2,3],[4,5]]
sum = 0
for i in list2d:
    for j in i:
        sum += j

 

 

Published 352 original articles · won praise 115 · views 130 000 +

Guess you like

Origin blog.csdn.net/Aidam_Bo/article/details/104679377