“添加到设置"在Java中返回布尔值-python呢? [英] "add to set" returns a boolean in java - what about python?
问题描述
在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呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!