、add()
は常にバックNone
を与えるが、「賢く」サブクラスを使用してからあなたを防ぐためには何もありません:
class sset(set):
"""return True if on add if an object was really added (and not in yet)"""
def add(self, val):
if val in self:
return True
set.add(self, val)
return False
これは、あなたが書くことができます:
s = sset()
if s.add('1'):
print('try 1')
if s.add('1'):
print('try 2')
と実行時にtry 2
が表示されます。
は、これは簡単に非効率性を含めることができます@ brandizzi年代のように複数行のコードを繰り返さないようにします。
:yは、それがすでにある場合でも追加されると、非効率的である
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
それは 何かのようにする必要がありますsset()
で
z = set()
was_here = y not in z
if not was_here:
z.add(y)
else: # If the object was not in the list yet...
print something
これはに減らすことができます。
z = sset()
if z.add(y): # If the object was not in the list yet...
print something
コンソールで 'type(z.add(y))'を実行すると、これらのことを自分で確認できます。ここでの結果は '' –
Oliver