简体   繁体   中英

How to check the shape of multiple arrays contained in a list?

I got a list containing multiple arrays, and I wrote the following codes try to see shape[0] of these arrays,

for i in xrange(len(list)):
    k = list[i].shape[0]
    print k

the outputs were correct, but I want to check these shape[0], that is, if they are the same, the function would continue, otherwise, if they are not the same number, the function breaks. How to do this? Feel free to give me advice, thanks a lot.

Update

I created a list named 'ab' containing 3 different arrays, and used errors and exceptions codes to check the shape[0]:

ab = [np.array([[1,2,3],[1,2,3]]), 
      np.array([[1,2,3]]), 
      np.array([[1,2,3],[1,2,3],[0,1,2],[0,9,9]])]

for i in xrange(len(ab)):
k = ab[i].shape[0]
print k

try:
    all(x.shape[0]==ab[0].shape[0] for x in ab)
    print 'True'
except ValueError:
    print 'False'

but the outputs were:

2
1
4
True

the outputs were wrong, where did I make a mistake?

all(x.shape[0]==list[0].shape[0] for x in list)

You can use a set comprehension to create a set of unique shapes then check if the length of the set is more than 1:

shapes = {arr.shape[0] for arr in my_list}
if len(shapes) > 1:
    # return None

Or as a better way try to apply a numpy function on your array, if they are not in same shape it will raise a ValueError :

try:
    np.hstack(my_list)
except ValueError:
    # rasise exception or return None

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM