![](/img/trans.png)
[英]How to use python's Structural Pattern Matching to test built in types?
[英]How to distinguish between a tuple and a list in Python's 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)])
输出:
single point: (1, 1)
single point: ((1, 1), (2, 2))
而我想要它 output:
single point: (1, 1)
list of points:
(1, 1)
(2, 2)
切换 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)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.