j0n*_*0ss 5 python structural-pattern-matching
我有一个对象列表,想要检查列表的一部分是否与特定模式匹配。
考虑以下列表:
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 对象)
def struct_match(lst_target, lst_pattern):
for i in range(len(lst_target)-(len(lst_pattern)-1)):
if lst_target[i:i+len(lst_pattern)] == lst_pattern:
print('matched!')
break
Run Code Online (Sandbox Code Playgroud)
l1 = ["foo", "bar"]
l2 = [{1, 2},"foo", "bar"]
l3 = ["foo", "bar", 5]
l4 = [{1,2},"foo", "bar", 5, 6]
l5 = [{1,2},"foo", "baz", "bar", 5, 6]
patt = ["foo", "bar"]
struct_match(l1, patt)
struct_match(l2, patt)
struct_match(l3, patt)
struct_match(l4, patt)
struct_match(l5, patt)
# outputs
matched!
matched!
matched!
matched!
Run Code Online (Sandbox Code Playgroud)
PS:我刚刚在这里找到了一个漂亮的递归解决方案(递归总是很漂亮......如果你的列表不太长)