`set.add` 没有返回值有什么原因吗?
当前,因为 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
。
原因是集合修改器,如 set.add()、list.append() 等,永远不会返回值。
如果方法发生变化并成为对象,则它不会返回值。这就是规则。
有一些小的例外,例如
pop
。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
.如果 s.add 始终返回 None,那么您的条件将始终为 True。但由于 s 是一个集合,只需将值添加到其中即可。根据定义,集合中不能有重复的值:
如果您只想知道集合中是否有 1,则执行
if 1 in s
。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 :
If you just want to know if 1 is in the set, then do
if 1 in s
.