In generale potrebbe significare qualsiasi cosa. È stato già spiegato cosa significa se è un list
o ma in generale dipende solo da come gli operatori di confronto (<
, >
, ...) e anche come viene implementato l'elemento get/set ([...]
-syntax) .
x.__getitem__(x.__lt__(2)) # this is what x[x < 2] means!
x.__setitem__(x.__lt__(2), 0) # this is what x[x < 2] = 0 means!
Poiché:
x < value
è equivalente a x.__lt__(value)
x[value]
è (approssimativamente) equivalente a x.__getitem__(value)
x[value] = othervalue
è (anche approssimativamente) equivalente a x.__setitem__(value, othervalue)
.
Questo può essere personalizzato per fare qualsiasi cosa che vuoi. A titolo di esempio (imita un po 'di indicizzazione numpys-booleana):
class Test:
def __init__(self, value):
self.value = value
def __lt__(self, other):
# You could do anything in here. For example create a new list indicating if that
# element is less than the other value
res = [item < other for item in self.value]
return self.__class__(res)
def __repr__(self):
return '{0} ({1})'.format(self.__class__.__name__, self.value)
def __getitem__(self, item):
# If you index with an instance of this class use "boolean-indexing"
if isinstance(item, Test):
res = self.__class__([i for i, index in zip(self.value, item) if index])
return res
# Something else was given just try to use it on the value
return self.value[item]
def __setitem__(self, item, value):
if isinstance(item, Test):
self.value = [i if not index else value for i, index in zip(self.value, item)]
else:
self.value[item] = value
Così ora vediamo cosa succede se lo si utilizza:
>>> a = Test([1,2,3])
>>> a
Test ([1, 2, 3])
>>> a < 2 # calls __lt__
Test ([True, False, False])
>>> a[Test([True, False, False])] # calls __getitem__
Test ([1])
>>> a[a < 2] # or short form
Test ([1])
>>> a[a < 2] = 0 # calls __setitem__
>>> a
Test ([0, 2, 3])
Avviso questa è solo una delle possibilità. Sei libero di implementare quasi tutto ciò che desideri.
non ha mai senso farlo con una lista. – dbliss
Questo ha senso solo con gli array NumPy o oggetti simili, che si comportano in modo completamente diverso dal comportamento negli esperimenti o dal comportamento basato su elenchi spiegato in entrambe le risposte. – user2357112
Nota, questo non funziona in Python 3. I tipi possono essere confrontati solo quando il confronto ha senso. In Python 3 questo esempio lancia 'TypeError: types non ordinabili: list()