【发布时间】:2021-08-10 16:04:56
【问题描述】:
这与新的 Python 3.10 测试版和新的 match 语法有关。
有没有办法检查一个模式是否简单地包含在一个迭代中?最明显的解决方案是简单地将两个通配符放在两边,但由于来自可迭代解包的解包语法,这会引发SyntaxError。
有没有办法做到这一点?
注意:在numbers 周围使用诸如包装类之类的东西
在这个例子中会很好,只要它使用匹配块并且至少有点可读,但是我已经尝试过这个并且没有太大的成功
示例:
numbers = [1, 2, 3, 5, 7, 8, 9] #does not have to be a list, could be a class if needed
match numbers:
# this just raises a SyntaxError, but I need a way to do something equivalent to this
case [*_, (5 | 6), *_]:
print("match!")
【问题讨论】:
-
使用 any() 怎么样?
-
any() 不能用于 match 语句,也不能用于任何函数;你得到的确切错误是
TypeError: called match pattern must be a type -
使用旧版python:
print any([not not re.match(pattern, str(n)) for n in numbers]) -
if 5 in numbers or 6 in numbers:有什么问题?
标签: python iterable iterable-unpacking python-3.10 structural-pattern-matching