简体   繁体   English

为什么 Python 将列表匹配为元组?

[英]Why Python matches a list as a tuple?

With Python 3.11.0a2+, and the following code:使用 Python 3.11.0a2+ 和以下代码:

def my_fun(e):
    match e:
        case (1,):
            print("tuple (1,)")
        case [1]:
            print("list [1]")
        case _:
            print("I don't understand")

Calling the function with my_fun([1]) prints "tuple (1,)".使用my_fun([1])调用 function 会打印“元组 (1,)”。

Is this behavior correct?这种行为正确吗?

If I explicitly match against tuple((1, )) instead of (1,) , it works as expected.如果我明确匹配tuple((1, ))而不是(1,) ,它会按预期工作。

If this is not a bug of the interpreter, what is the reason behind this seemingly weird behavior?如果这不是解释器的错误,那么这种看似奇怪的行为背后的原因是什么?

This isdocumented under Structural Pattern Matching .记录在结构模式匹配

Like unpacking assignments, tuple and list patterns have exactly the same meaning and actually match arbitrary sequences .与解包赋值一样,元组和列表模式具有完全相同的含义,并且实际上匹配任意序列 Technically, the subject must be a sequence.从技术上讲,主题必须是一个序列。 Therefore, an important exception is that patterns don't match iterators.因此,一个重要的例外是模式与迭代器不匹配。 Also, to prevent a common mistake, sequence patterns don't match strings.此外,为了防止常见错误,序列模式不匹配字符串。

and in PEP 635 -- Structural Pattern Matching: Motivation and Rationale并在PEP 635 -- 结构模式匹配:动机和基本原理

As in iterable unpacking, we do not distinguish between ' tuple ' and ' list ' notation.与可迭代拆包一样,我们不区分“元组”和“列表”表示法。 [a, b, c] , (a, b, c) and a, b, c are all equivalent. [a, b, c] , (a, b, c)a, b, c都是等价的。 While this means we have a redundant notation and checking specifically for lists or tuples requires more effort (eg case list([a, b, c])) , we mimic iterable unpacking as much as possible.虽然这意味着我们有一个冗余的符号并且专门检查列表或元组需要更多的努力(例如 case list([a, b, c])) ,但我们尽可能地模仿可迭代解包。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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