简体   繁体   English

Python的结构模式匹配中如何区分元组和列表?

[英]How to distinguish between a tuple and a list in Python's structural pattern matching?

I want to use Python's structural pattern matching to distinguish between a tuple (eg representing a point) and a list of tuples.我想使用 Python 的结构模式匹配来区分元组(例如表示一个点)和元组列表。

The straightforward approach does not work though:直截了当的方法不起作用:

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

which outputs:输出:

single point: (1, 1)
single point: ((1, 1), (2, 2))

whereas I want it to output:而我想要它 output:

single point: (1, 1)
list of points:
(1, 1)
(2, 2)

Switching the order of the case statements also does not help here.切换 case 语句的顺序在这里也无济于事。

What is a good way to solve this with pattern matching?用模式匹配解决这个问题的好方法是什么?

Use tuple(foo) for matching a tuple and list(foo) for matching a list使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM