python - Python中有这样的模式匹配函数吗?

标签 python lisp scheme pattern-matching racket

我刚找到 pattern matching Racket 中的功能非常强大。

> (match '(1 2 3) [(list a b c) (list c b a)])

'(3 2 1)

> (match '(1 2 3) [(list 1 a ...) a])

'(2 3)

> (match '(1 2 3)
    [(list 1 a ..3) a]
    [_ 'else])

'else

> (match '(1 2 3 4)
    [(list 1 a ..3) a]
    [_ 'else])

'(2 3 4)

> (match '(1 2 3 4 5)
    [(list 1 a ..3 5) a]
    [_ 'else])

'(2 3 4)

> (match '(1 (2) (2) (2) 5)
    [(list 1 (list a) ..3 5) a]
    [_ 'else])

'(2 2 2)

在 Python 中是否有类似的语法糖或库来做到这一点?

最佳答案

不不不,python的模式匹配只是这样的可迭代解包:

>>> (x, y) = (1, 2)
>>> print x, y
1 2

或者在函数定义中:

>>> def x((x, y)):
    ...

或者在 python 3 中:

>>> x, *y = (1, 2, 3)
>>> print(x)
1
>>> print(y)
[2, 3]

但是有一些external libraries实现模式匹配。

关于python - Python中有这样的模式匹配函数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11909681/

相关文章:

python - 在 Python 中使输入可选

macros - 在运行时处理内部变量和数据结构的 LISP 宏

"or"的方案宏

Python 切片运算符 : Negative start combined with Positive stop

python - 套接字碎片接收数据

python - 更新根证书失败: cacert. pem

macros - Lisp 宏在我不希望它时评估表达式

lisp - 为什么 lisp 使用 gensym 而其他语言不使用?

matrix - 获取矩阵中的对角线

python - Python中SymbolType有什么用?