【问题标题】:How to distinguish between a tuple and a list in Python's structural pattern matching?Python结构模式匹配中如何区分元组和列表?
【发布时间】: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


【解决方案1】:

使用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)]

【讨论】:

    猜你喜欢
    • 2016-06-04
    • 2021-05-04
    • 2019-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多