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

2022-09-03 13:05:53

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

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

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

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

但它不打印任何东西。我错过了什么吗?感谢!


答案 1

在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


答案 2

如前面的答案中所述,Python 集的 add 方法不会返回任何内容。顺便说一句,这个确切的问题在Python邮件列表上进行了讨论:http://mail.python.org/pipermail/python-ideas/2009-February/002877.html