首页 > 解决方案 > 检查元组内的数组在Python中是否为空

问题描述

在我的代码中,我有一行,它查找numpy.ndarray类型设置为 1 的值:

neg_samples = np.where(Y1[0, :, -1] == 1)

它使用print(neg_samples)这样的元组返回:

(array([ 0, 1, 2]),)

但有时数组为空,结果如下:

(array([], dtype=int64),)

我需要检查这个数组是否为空。我试过:

   if len(neg_samples) > 0:
       neg_samples = neg_samples[0]
   else:
       neg_samples = []

但是每次,每次它都在继续,所以我决定检查它的长度,它neg_samples看起来就像每次,无论何时,无论何时。(array([], dtype=int64),)(array([ 0, 1, 2(...), 199, 200]),)len(neg_samples)=1

使用if not all(neg_samples):抛出

ValueError: The truth value of an array with more than one element is ambiguous.

我认为问题在于数组在元组内。如何检查这个元组中的这个数组是否为空?

标签: python

解决方案


In [54]: a = (array.array('d', []),)

In [55]: len(a)
Out[55]: 1

In [56]: len(a[0])
Out[56]: 0

在继续之前检查 len


推荐阅读