Python范围替代

时间:2019-01-23 13:29:39

标签: python loops syntax numbers

for i in range(10):

for i in 0 .. 9:

如何“超载”? '..'。

我发现range()对象不简洁或不易阅读。 Pascal注释/语法(范围(包括..包括)http://rigaux.org/language-study/syntax-across-languages-per-language/Pascal.html)非常容易阅读。

我在pathlib模块https://docs.python.org/3/library/pathlib.html中看到它重载了(?)/字符。

1 个答案:

答案 0 :(得分:0)

虽然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)

不幸的是,不是我的主意,请参阅this brilliant post for the original idea