2017-08-25 77 views
-3

我有一个简单的脚本返回不少误区:什么错这个python脚本

import numpy as np 
def test(array): 
    ncol=np.shape(array)[1] 
    return ncol 

这应该返回数组的列数。它有什么问题?数组是numpy数组。下面是输出:

ncol=np.shape(array)[1] Display all 195 possibilities? (y or n) ArithmeticError( continue AssertionError( copyright( AttributeError( credits( BaseException( def BlockingIOError( del

+0

它返回什么错误? 'array'的价值是什么? – msanford

+0

我添加了错误。数组是一个numpy数组 –

+1

你如何使用脚本?你为了获得上述错误而发布的显式命令是什么? –

回答

1

您需要添加一个try.. catch围绕ncol=np.shape(array)[1],因为它没有当数组是一维尺寸:

import numpy as np 

arr = np.random.normal(size=10) 
arr1 = np.random.normal(size=(10,5)) 

def test(array): 
    try: 
     ncol=np.shape(array)[1] 
     return ncol 
    except Exception as e: 
     print("no columns in array") 
     return None 

print(test(arr)) 
# output: 
# no columns in array 
# None 

print(test(arr1)) 
# output: 
# 5