use*_*696 6 python arrays tuples numpy
我在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)
Run Code Online (Sandbox Code Playgroud)
但是,当我在寻找字符串数组中不存在的字母时,我得到一个空元组,如下所示:
(array([], dtype=int64),)
Run Code Online (Sandbox Code Playgroud)
我需要能够检测到它何时找不到我在数组中寻找的字母.
我尝试过以下方法:
if not letter_found:
print 'not found'
Run Code Online (Sandbox Code Playgroud)
但这不起作用.如何检测tuple
where函数返回的numpy
是空的?是因为我的一个变量可能是错误的类型?我是新手python
和编程.
whe*_*ies 12
命名:
if some_iterable:
#only if non-empty
Run Code Online (Sandbox Code Playgroud)
只有在某些东西空的时候才有效 在你的情况下,元组实际上不是空的.元组包含的东西是空的.所以你可能想要做以下事情:
if any(map(len, my_tuple)):
#passes if any of the contained items are not empty
Run Code Online (Sandbox Code Playgroud)
因为len
在一个空的iterable将产生0
,因此将转换为False
.