【发布时间】:2021-12-30 04:41:42
【问题描述】:
我想使用 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))
而我希望它输出:
single point: (1, 1)
list of points:
(1, 1)
(2, 2)
切换 case 语句的顺序在这里也无济于事。
用模式匹配解决这个问题的好方法是什么?
【问题讨论】:
-
*points 是一个列表,所以你可以使用
case *points:吗?还是把它放在另一个案例之前(上方)? -
您的第一个案例可以显式匹配包含两个整数的元组 -
case (int(x), int(y)):? -
@balmy 这将是一个语法错误。问题似乎是python对待所有序列都是一样的
-
@IainShelvington 确实有效!但是是否还有更通用的方法,比如元组内容是任意的?
-
@mihi 是的,我在下面添加了一个答案以及如何匹配元组或列表的示例
标签: python python-3.10 structural-pattern-matching