按行(列)存盤格式


import numpy as np
import random
from matplotlib import pyplot as plt
plt.rcParams['font.sans-serif']=['SimHei']
plt.rcParams['axes.unicode_minus'] = False
# matplotlib畫圖中中文顯示會有問題,需要這兩行設定默認字體
def sanju(A):
VA = []
IA = []
JA = []
for i in range(A.shape[0]):
for j in range(A.shape[1]):
if A[i, j] != 0:
VA.append(i)
IA.append(j)
JA.append(A[i, j])
print(VA, '\n', IA, '\n', JA, '\n')
return VA, IA, JA
def anrows(A):
VA = []
JA = []
IA = [0 for i in range(A.shape[0])]
count = 0
for i in range(A.shape[0]):
cs = count
f2 = 0
count = 0
for j in range(A.shape[1]):
if A[i, j] != 0:
count = count + 1
VA.append(A[i, j])
JA.append(j)
f2 = 1 # 檢測是否有非零元素,如果有,1,沒有,0;
if i > 0 and IA[i - 1] > 0:
IA[i] = IA[i - 1] + cs
elif i > 0 and IA[i - 1] == 0 and f2 == 1:
IA[i] = 1
elif f2 == 1 and i == 0:
IA[i] = 1
elif f2 == 0 and i == 0:
IA[i] = 0
c = [i for i in range(A.shape[0])]
for i in range(A.shape[0]-1):
for j in range(IA[i], IA[i + 1]):
if IA[i] > 0:
print(f'({i}, {JA[j-1]}):{VA[j - 1]} ', end=' ')
print('')
i = i + 1
for j in range(IA[i], len(VA)+1):
if IA[i] > 0:
print(f'({i}, {JA[j-1]}):{VA[j - 1]} ', end=' ')
print('')
return VA, JA, IA
A = np.mat(np.zeros((10, 10)))
for i in range(100):
a = random.randint(0, 9)
b = random.randint(0, 9)
A[a, b] = a*b
VAa, JAa, IAa = anrows(A)
print(A)

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/227849.html
標籤:python
