python 中的函数什么都不返回

发布于 2024-12-28 21:14:46 字数 249 浏览 2 评论 0原文

我有这个数组,

     a = array([1,5,7])

我应用了 where 函数

     where(a==8)

在这种情况下返回的是

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

但是我希望代码在 where 函数返回空数组时返回整数“0”。这可能吗?

I have this array

     a = array([1,5,7])

I apply the where function

     where(a==8)

What is returned in this case is

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

However I would like the code to return the integer "0" whenever the where function returns an empty array. Is that possible?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

海夕 2025-01-04 21:14:46
def where0(vec):
    a = where(vec)
    return a if a[0] else 0
    # The return above is equivalent to:
    # if len(a[0]) == 0:
    #     return 0  # or whatever you like
    # else:
    #     return a

a = array([1,5,7])
print where0(a==8)

还要考虑您的问题下 aix 的评论。不要修复 where(),而是修复你的算法

def where0(vec):
    a = where(vec)
    return a if a[0] else 0
    # The return above is equivalent to:
    # if len(a[0]) == 0:
    #     return 0  # or whatever you like
    # else:
    #     return a

a = array([1,5,7])
print where0(a==8)

And consider also the comment from aix under your question. Instead of fixing where(), fix your algorithm

◇流星雨 2025-01-04 21:14:46

最好使用只有一种返回类型的函数。您可以检查数组的大小以了解它是否为空,这应该可以完成工作:

 a = array([1,5,7])
 result = where(a==8)

 if result[0] != 0:
     doFancyStuff(result)
 else:
     print "bump"

Better use a function that has only one return type. You can check for the size of the array to know if it's empty or not, that should do the work:

 a = array([1,5,7])
 result = where(a==8)

 if result[0] != 0:
     doFancyStuff(result)
 else:
     print "bump"
趁微风不噪 2025-01-04 21:14:46

空数组将返回 0 和 .size

import numpy as np    
a = np.array([])    
a.size
>> 0

a empty array will return 0 with .size

import numpy as np    
a = np.array([])    
a.size
>> 0
来世叙缘 2025-01-04 21:14:46

尝试下面的方法。这将处理返回索引 0 时等于 0 的测试失败的情况。 (例如以下情况下的 np.where(a==1))

a = array([1,5,7])
ret = np.where(a==8)
ret = ret if ret[0].size else 0

Try the below. This will handle the case where a test for equality to 0 will fail when index 0 is returned. (e.g. np.where(a==1) in the below case)

a = array([1,5,7])
ret = np.where(a==8)
ret = ret if ret[0].size else 0
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文