gpt4 book ai didi

python - 结构模式匹配python——匹配序列任意位置

转载 作者:行者123 更新时间:2023-12-05 04:23:58 24 4
gpt4 key购买 nike

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

考虑以下列表:

l1 = ["foo", "bar"]
l2 = [{1, 2},"foo", "bar"]
l3 = ["foo", "bar", 5]
l4 = [{1,2},"foo", "bar", 5, 6]

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

我天真的想法是:

match l4:
case [*_, "foo", "bar", *_]:
print("matched!")

不幸的是,这是一个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
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!

PS:我刚刚找到了一个漂亮的递归解决方案here (递归总是美好的……如果你的列表不是太长的话)

关于python - 结构模式匹配python——匹配序列任意位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73594044/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com