python - 为什么我无法检测到元组为空?

标签 python arrays numpy tuples

我在numpy中使用where函数在字符串数组中查找一个字母字符串。
例如:
我将在'U'中寻找['B' 'U' 'A' 'M' 'R' 'O']并获取'U'的索引。

letter = 'U'
row = ['B', 'U', 'A', 'M', 'R', 'O']
letter_found = np.where(row == letter)

但是,当我寻找字符串数组中不存在的字母时,我得到一个空的元组,看起来像这样:
(array([], dtype=int64),)

我需要能够检测何时在数组中找不到我要查找的字母。

我尝试了以下方法:
if not letter_found:
    print 'not found'

但这是行不通的。如何检测从tuple中的where函数返回的numpy为空?是否因为我的变量之一可能是错误的类型?我是python和一般编程的新手。

最佳答案

命名法:

if some_iterable:
    #only if non-empty
仅当空的东西时起作用。在您的情况下,元组实际上不是空的。元组包含的东西是空的。因此,您可能需要执行以下操作:
if any(map(len, my_tuple)):
    #passes if any of the contained items are not empty
因为空的iterable上的len将产生0,因此将被转换为False

关于python - 为什么我无法检测到元组为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23370921/

相关文章:

python - 如何在 QMainWindow 中创建菜单栏

python - 尝试使用 BeautifulSoup 访问 XML 中的嵌套元素

python - 使用 numpy 数组和元组保持每个元素出现一次的快速方法

ios - TableView、数组和 segue

python - 序列化 Numpy 数组的意外行为

python - 快速将数组分配给长度相等的 n 个 bin

python / NumPy : How do you assign the end+1 element of an array similar to how it's done in Matlab?

python - 使用 Python XPath 表达式提取文本

C++ : Arrays and memory locations

php - 将日期数组拆分为连续的日期数组