“ add to set”在Java中返回一个布尔值-python呢?


问题内容

在Java中,我喜欢使用“添加到集合”操作返回的布尔值来测试元素是否已经存在于集合中:

if (set.add("x")) {
   print "x was not yet in the set";
}

我的问题是,Python中有什么方便的东西吗?我试过了

 z = set()
 if (z.add(y)):
     print something

但它不会打印任何内容。我想念什么吗?谢谢!


问题答案:

在Python中,该set.add()方法不返回任何内容。您必须使用not in运算符:

z = set()
if y not in z: # If the object is not in the list yet...
    print something
z.add(y)

如果 确实 需要在添加对象之前知道对象是否在集合中,则只需存储布尔值:

z = set()
was_here = y not in z
z.add(y)
if was_here: # If the object was not in the list yet...
    print something

但是,我认为您不太可能需要它。

这是Python的一种约定:当方法更新某些对象时,它会返回None。您可以忽略此约定;此外,还有一些“野外”的方法违反了它。但是,这是一个公认的通用惯例:我建议您坚持并记住这一点。