在 Java 中,我喜欢使用添加到集合"操作返回的布尔值来测试该元素是否已经存在于集合中:
In Java I like to use the Boolean value returned by an "add to the set" operation to test whether the element was already present in the set:
if (set.add("x")) {
print "x was not yet in the set";
}
我的问题是,在 Python 中有没有这样方便的东西?我试过了
My question is, is there something as convenient in Python? I tried
z = set()
if (z.add(y)):
print something
但它不打印任何东西.我错过了什么吗?谢谢!
But it does not print anything. Am I missing something? Thx!
在 Python 中,set.add()
方法不返回任何内容.您必须使用 not in
运算符:
In Python, the set.add()
method does not return anything. You have to use the not in
operator:
z = set()
if y not in z: # If the object is not in the list yet...
print something
z.add(y)
如果您真的需要在添加之前知道对象是否在集合中,只需存储布尔值即可:
If you really need to know whether the object was in the set before you added it, just store the boolean value:
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
但是,我认为您不太可能需要它.
However, I think it is unlikely you need it.
这是一个 Python 约定:当一个方法更新某个对象时,它返回 None
.你可以忽略这个约定;此外,还有一些在野外"违反它的方法.然而,这是一个普遍的、公认的惯例:我建议您坚持并牢记这一点.
This is a Python convention: when a method updates some object, it returns None
. You can ignore this convention; also, there are methods "in the wild" that violate it. However, it is a common, recognized convention: I'd recommend to stick to it and have it in mind.
这篇关于“添加到集合"在java中返回一个布尔值-python呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!