我刚找到 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/