在Python中,该
set.add()方法不返回任何内容。您必须使用
not in运算符:
z = set()if y not in z: # If the object is not in the list yet... print somethingz.add(y)
如果 确实 需要在添加对象之前知道对象是否在集合中,则只需存储布尔值:
z = set()was_here = y not in zz.add(y)if was_here: # If the object was not in the list yet... print something
但是,我认为您不太可能需要它。
这是Python的一种约定:当方法更新某些对象时,它会返回
None。您可以忽略此约定;此外,还有一些“野外”的方法违反了它。但是,这是一个公认的通用惯例:我建议您坚持并记住这一点。



