在Java中,我喜欢使用"添加到集合"操作返回的布尔值来测试元素是否已经存在于集合中:
if (set.add("x")) {
print "x was not yet in the set";
}
Run Code Online (Sandbox Code Playgroud)
我的问题是,Python中有什么方便吗?我试过了
z = set()
if (z.add(y)):
print something
Run Code Online (Sandbox Code Playgroud)
但它没有打印任何东西.我错过了什么吗?谢谢!
bra*_*zzi 11
在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)
Run Code Online (Sandbox Code Playgroud)
如果在添加对象之前确实需要知道对象是否在集合中,只需存储布尔值:
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
Run Code Online (Sandbox Code Playgroud)
但是,我认为你不太可能需要它.
这是一个Python约定:当一个方法更新某个对象时,它会返回None
.你可以忽略这个惯例; 此外,有一些"野外"的方法违反了它.然而,这是一个普遍的,公认的惯例:我建议坚持下去,并牢记它.
正如前面的答案中提到的,Python 集合的 add 方法不返回任何内容。顺便说一下,这个确切的问题在 Python 邮件列表中讨论过:http : //mail.python.org/pipermail/python-ideas/2009-February/002877.html。
归档时间: |
|
查看次数: |
5873 次 |
最近记录: |