小编j0n*_*0ss的帖子

结构模式匹配python - 匹配序列中的任何位置

我有一个对象列表,想要检查列表的一部分是否与特定模式匹配。

考虑以下列表:

l1 = ["foo", "bar"]
l2 = [{1, 2},"foo", "bar"]
l3 = ["foo", "bar", 5]
l4 = [{1,2},"foo", "bar", 5, 6]
Run Code Online (Sandbox Code Playgroud)

["foo", "bar"]在所有不同情况下我将如何匹配序列?

我天真的想法是:

match l4:
    case [*_, "foo", "bar", *_]:
        print("matched!")
Run Code Online (Sandbox Code Playgroud)

不幸的是,这是一个SyntaxError: multiple starred names in sequence pattern. 问题是,我不知道有多少元素在该模式的前面和后面。

编辑:我想我需要澄清:"foo", "bar"只是一个更复杂模式的替代品。(我正在使用 AST 对象)

python structural-pattern-matching

5
推荐指数
1
解决办法
914
查看次数