mih*_*ihi 3 python python-3.10 structural-pattern-matching
我想使用Python的结构模式匹配来区分元组(例如代表一个点)和元组列表。
但直接的方法不起作用:
def fn(p):
match p:
case (x, y):
print(f"single point: ({x}, {y})")
case [*points]:
print("list of points:")
for x, y in points:
print(f"({x}, {y})")
fn((1, 1))
fn([(1, 1), (2, 2)])
Run Code Online (Sandbox Code Playgroud)
其输出:
single point: (1, 1)
single point: ((1, 1), (2, 2))
Run Code Online (Sandbox Code Playgroud)
而我希望它输出:
single point: (1, 1)
list of points:
(1, 1)
(2, 2)
Run Code Online (Sandbox Code Playgroud)
切换 case 语句的顺序在这里也没有帮助。
通过模式匹配解决这个问题的好方法是什么?
用于tuple(foo)匹配元组和list(foo)匹配列表
def fn(p):
match p:
case tuple(contents):
print(f"tuple: {contents}")
case list(contents):
print(f"list: {contents}")
fn((1, 1)) # tuple: (1, 1)
fn([(1, 1), (2, 2)]) # list: [(1, 1), (2, 2)]
Run Code Online (Sandbox Code Playgroud)