quot;add to setquot; returns a boolean in java - what about python?(“添加到集合在java中返回一个布尔值-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呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:“添加到集合"在java中返回一个布尔值-python呢?
基础教程推荐
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- 降序排序:Java Map 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01