def matrixDimensions(m):
""" function that returns the dimensions of a matrix. """
mRowNum= len(m) # this is the number of rows
mColNum=len(m[0])# this is the size of columns in row 1
i=1
j=1
if mRowNum ==1: # if there is only one row , don't need to check for identical columns
return "This is a %ix%i matrix." %(mRowNum,mColNum)
ColNum=len(m[i])# # this is the size of columns in row 2
if mRowNum>1:# this is where you need to check all the columns are identical
while i< mRowNum:
i+=1
if len(m[j])== len(m[0]):
print (i,j,mRowNum,ColNum,m[j],len(m[j]))
j+=1
continue
elif len(m[j])!= len(m[0]):
return 'This is not a valid matrix.'
return "This is a %ix%i matrix." %(mRowNum,mColNum)
必须有更简单的逻辑,如何检查嵌套的列表,例如我认为这不是一个有效的矩阵,但会通过此测试。
([ [1,4, 3], [4,0,21],[3,4,[5,7]],[1,2,3],[1,2,3]])
答案 0 :(得分:1)
你可以尝试这样的事情:
def are_int(iterable):
return all(isinstance(i, int) for i in iterable)
def matrix_dimensions(matrix):
col = len(matrix[0])
if not all(len(l) == col and are_int(l) for l in matrix):
return 'This is not a valid matrix'
else:
return len(matrix), col
m = [[1,4,3], [4,0,21], [3,4,[5,7]], [1,2,3], [1,2,3]]
l = [[1,4,3], [4,0,21], [3,4,7], [1,2,3], [1,2,3]]
print(matrix_dimensions(m))
print(matrix_dimensions(l))
输出:
This is not a valid matrix
(5, 3)