问题:如果set为空,则返回布尔值

如果我的函数集结尾为空,我正在努力寻找一种更干净的返回布尔值的方法

我将两个集合相交,并希望返回TrueFalse基于结果集是否为空。

def myfunc(a,b):
    c = a.intersection(b)
    #...return boolean here

我最初的想法是

return c is not None

但是,在我的解释器中,我可以很容易地看到,如果 c = set([])

>>> c = set([])
>>> c is not None
True

我还尝试了以下所有方法:

>>> c == None
False
>>> c == False
False
>>> c is None
False

现在,我已经从文档阅读,我只能用andornot空集来推断一个布尔值。到目前为止,我唯一能想到的就是不返回

>>> not not c
False
>>> not c
True

我感觉有一种更多的Python方式可以做到这一点,因为我一直在努力寻找它。我不想将实际集合返回到if语句,因为我不需要这些值,我只想知道它们是否相交。

I am struggling to find a more clean way of returning a boolean value if my set is empty at the end of my function

I take the intersection of two sets, and want to return True or False based on if the resulting set is empty.

def myfunc(a,b):
    c = a.intersection(b)
    #...return boolean here

My initial thought was to do

return c is not None

However, in my interpreter I can easily see that statement will return true if c = set([])

>>> c = set([])
>>> c is not None
True

I’ve also tried all of the following:

>>> c == None
False
>>> c == False
False
>>> c is None
False

Now I’ve read from the documentation that I can only use and, or, and not with empty sets to deduce a boolean value. So far, the only thing I can come up with is returning not not c

>>> not not c
False
>>> not c
True

I have a feeling there is a much more pythonic way to do this, by I am struggling to find it. I don’t want to return the actual set to an if statement because I don’t need the values, I just want to know if they intersect.


回答 0

def myfunc(a,b):
    c = a.intersection(b)
    return bool(c)

会执行类似的操作not not,但在意识形态上更清晰。

def myfunc(a,b):
    c = a.intersection(b)
    return bool(c)

will do something similar to not not, but more ideomatic and clear.


回答 1

不像其他答案那样具有pythonic功能,而是数学功能:

return len(c) == 0

正如一些评论想知道的那样,这len(set)可能会对复杂性产生影响。如源代码中所示,它是O(1),因为它依赖于跟踪集合用法的变量。

static Py_ssize_t
set_len(PyObject *so)
{
    return ((PySetObject *)so)->used;
}

not as pythonic as the other answers, but mathematics:

return len(c) == 0

As some comments wondered about the impact len(set) could have on complexity. It is O(1) as shown in the source code given it relies on a variable that tracks the usage of the set.

static Py_ssize_t
set_len(PyObject *so)
{
    return ((PySetObject *)so)->used;
}

回答 2

如果您想要return True一个空集,那么我认为这样做会更清晰:

return c == set()

即“c等于空set”。

(或者,反之亦然return c != set())。

在我看来,这比False在布尔值上下文中依赖Python对空集的解释更为明确(尽管较少习惯用法)。

If you want to return True for an empty set, then I think it would be clearer to do:

return c == set()

i.e. “c is equal to an empty set“.

(Or, for the other way around, return c != set()).

In my opinion, this is more explicit (though less idiomatic) than relying on Python’s interpretation of an empty set as False in a boolean context.


回答 3

如果c为set,则可以通过执行以下操作检查它是否为空return not c

如果c为空,那么not cTrue

否则,如果c包含任何元素not c将为False

If c is a set then you can check whether it’s empty by doing: return not c.

If c is empty then not c will be True.

Otherwise, if c contains any elements not c will be False.


回答 4

当你说:

c is not None

您实际上正在检查c和None是否引用相同的对象。这就是“ is”运算符的作用。在python中,按常规,None是一个特殊的空值,表示您没有可用的值。像c或java中的null之类的sorta。由于python在内部仅使用“ is”运算符分配一个None值来检查某项是否为None(认为null)有效,因此它已成为流行的样式。但是,这与集合c的真值无关,它正在检查c实际上是一个集合,而不是空值。

如果要检查条件语句中的集合是否为空,则在上下文中将其强制转换为布尔值,因此您可以这样说:

c = set()
if c:
   print "it has stuff in it"
else:
   print "it is empty"

但是,如果您希望将其转换为布尔值以进行存储,则可以简单地说:

c = set()
c_has_stuff_in_it = bool(c)

When you say:

c is not None

You are actually checking if c and None reference the same object. That is what the “is” operator does. In python None is a special null value conventionally meaning you don’t have a value available. Sorta like null in c or java. Since python internally only assigns one None value using the “is” operator to check if something is None (think null) works, and it has become the popular style. However this does not have to do with the truth value of the set c, it is checking that c actually is a set rather than a null value.

If you want to check if a set is empty in a conditional statement, it is cast as a boolean in context so you can just say:

c = set()
if c:
   print "it has stuff in it"
else:
   print "it is empty"

But if you want it converted to a boolean to be stored away you can simply say:

c = set()
c_has_stuff_in_it = bool(c)

回答 5

"""
This function check if set is empty or not.
>>> c = set([])
>>> set_is_empty(c)
True

:param some_set: set to check if he empty or not.
:return True if empty, False otherwise.
"""
def set_is_empty(some_set):
    return some_set == set()
"""
This function check if set is empty or not.
>>> c = set([])
>>> set_is_empty(c)
True

:param some_set: set to check if he empty or not.
:return True if empty, False otherwise.
"""
def set_is_empty(some_set):
    return some_set == set()

回答 6

不如bool(c)干净,但是使用三元是一个借口。

def myfunc(a,b):
    return True if a.intersection(b) else False

同样,也使用一些相同的逻辑,除非您将其用于其他用途,否则无需分配给c。

def myfunc(a,b):
    return bool(a.intersection(b))

最后,我假设您想要一个True / False值,因为您将使用它执行某种布尔测试。我建议通过简单地测试您需要的位置来跳过函数调用和定义的开销。

代替:

if (myfunc(a,b)):
    # Do something

也许这样:

if a.intersection(b):
    # Do something

Not as clean as bool(c) but it was an excuse to use ternary.

def myfunc(a,b):
    return True if a.intersection(b) else False

Also using a bit of the same logic there is no need to assign to c unless you are using it for something else.

def myfunc(a,b):
    return bool(a.intersection(b))

Finally, I would assume you want a True / False value because you are going to perform some sort of boolean test with it. I would recommend skipping the overhead of a function call and definition by simply testing where you need it.

Instead of:

if (myfunc(a,b)):
    # Do something

Maybe this:

if a.intersection(b):
    # Do something

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。