蟒蛇范围替代方案


for i in range(10):
for i in 0 .. 9:

如何"超载"? '..' .

我发现range()对象不简洁或易于阅读。帕斯卡符号/语法(范围(包括..)http://rigaux.org/language-study/syntax-across-languages-per-language/Pascal.html)更容易阅读。

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

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

不幸的是,不是我的想法,请参阅这篇精彩的帖子以了解原始想法

最新更新