沉浸020903 2022-04-23 19:13 采纳率: 78.9%
浏览 57
已结题

判断csv文件内容是否为矩阵,如果不是矩阵抛出异常,请问我的代码要怎么改

问题遇到的现象和发生背景
问题相关代码,请勿粘贴截图
import csv
class NotMatrixException(Exception):
    pass
class FileExistsError(Exception):
    pass
a=list()
p=0
q=0
b=list()
m=0
n=0
try:
    with open ('A.csv','r') as file:
        lines = csv.reader(file)
        for line in lines:
            a.append(line)
            q=len(line)
except FileExistsError:
    raise FileExistsError
print(a)
p=len(a)
print(p,q)
with open ('B.csv','r') as file:
    lines = csv.reader(file)
    for line in lines:
        b.append(line)
        n=len(line)
print(b)
m=len(b)
print(m,n)
bT=list(zip(b[0],b[1],b[2]))
print(bT)
c=list()
if q!=n:
    raise 'MatrixMultiError'
for m in range(p):
    d=list()
    for i in range(p):
        sum=0
        for j in range(n):
            try:
                sum+=int(a[i][j])*int(bT[j][i])
            except ValueError:
                raise NotMatrixException
        d.append(sum)
    c.append(d)
print(c)
with open ('C.csv','w',newline='') as file:
    writer = csv.writer(file)
    writer.writerows(c)

运行结果及报错内容

G:\python\venv\Scripts\python.exe G:/python/demo.py
Traceback (most recent call last):
File "G:\python\demo.py", line 42, in
sum+=int(a[i][j])*int(bT[j][i])
ValueError: invalid literal for int() with base 10: ''

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "G:\python\demo.py", line 44, in
raise NotMatrixException
main.NotMatrixException
[['1', '1', '1'], ['1', '1', ''], ['1', '1', '1']]
3 3
[['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9']]
3 3
[('1', '4', '7'), ('2', '5', '8'), ('3', '6', '9')]

进程已结束,退出代码1

我的解答思路和尝试过的方法
我想要达到的结果

判断csv文件内容是否为矩阵,如果不是矩阵抛出异常NotMatrixException

  • 写回答

2条回答 默认 最新

  • 关注

    不是矩阵抛出异常NotMatrixException 没有什么问题吧

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 5月1日
  • 已采纳回答 4月23日
  • 创建了问题 4月23日

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改