`set.add` 没有返回值有什么原因吗?

发布于 2024-10-03 19:11:04 字数 250 浏览 0 评论 0原文

当前,因为 set.add 的返回值始终为 None。我必须执行以下操作。

if 1 in s:
    print 'already found'
    return
s.add(1)

如果我可以就好了

if not s.add(1):
    print 'already found'
    return

Current, since the returned value from set.add is always None. I have to do the following.

if 1 in s:
    print 'already found'
    return
s.add(1)

Would it be nice if I can

if not s.add(1):
    print 'already found'
    return

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

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

发布评论

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

评论(2

忘东忘西忘不掉你 2024-10-10 19:11:05

任何原因 set.add 没有返回值

原因是集合修改器,如 set.add()、list.append() 等,永远不会返回值。

如果方法发生变化并成为对象,则它不会返回值。这就是规则。

有一些小的例外,例如 pop

Any reason there are no returned value from set.add

Yes.

The reason is that collection mutators, like set.add(), list.append(), etc., never return a value.

If a method mutates and object, it does not return a value. That's the rule.

There are minor exceptions, like pop.

〃温暖了心ぐ 2024-10-10 19:11:04
>>> None == False
False
>>> None == True
False
>>> None == None
True
>>> not None
True

如果 s.add 始终返回 None,那么您的条件将始终为 True。但由于 s 是一个集合,只需将值添加到其中即可。根据定义,集合中不能有重复的值:

>>> a = set()
>>> a.add(1)
>>> a
{1}
>>> a.add(1)
>>> a
{1}

如果您只想知道集合中是否有 1,则执行 if 1 in s

>>> None == False
False
>>> None == True
False
>>> None == None
True
>>> not None
True

If s.add always returns None, then your condition will always be True. But since s is a set, just add the value to it. You can't have duplicate values in a set, by definition :

>>> a = set()
>>> a.add(1)
>>> a
{1}
>>> a.add(1)
>>> a
{1}

If you just want to know if 1 is in the set, then do if 1 in s.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文