Хотя Python
не имеет оператора ..
, вы можете определить инфиксный оператор следующим образом:
class Infix:
def __init__(self, function):
self.function = function
def __ror__(self, other):
return Infix(lambda x, self=self, other=other: self.function(other, x))
def __or__(self, other):
return self.function(other)
def __rlshift__(self, other):
return Infix(lambda x, self=self, other=other: self.function(other, x))
def __rshift__(self, other):
return self.function(other)
def __call__(self, value1, value2):
return self.function(value1, value2)
Теперь выберите осмысленное имя, например until
, и все готово:
until = Infix(lambda x,y: range(x,y +1))
print(2 |until| 4)
# [2, 3, 4]
Или
for i in (2 |until| 4):
print(i)
К сожалению, не моя идея, см. этот блестящий пост для оригинальной идеи .