在关键字 Class 模式中出现语法错误

Getting Syntax Error in Keyword Class Patterns

城市class和一些实例

import typing

class City(typing.NamedTuple):
    continent: str
    name: str
    country: str


cities = [
    City('Asia', 'Tokyo', 'JP'),
    City('Asia', 'Delhi', 'IN'),
    City('North America', 'Mexico City', 'MX'),
    City('North America', 'New York', 'US'),
    City('South America', 'São Paulo', 'BR'),
]

The following function should return a list of Asian cities:

def match_asian_cities():
    results = []
    for city in cities:
        match city:
            case City(continent='Asia'):
                results.append(city)
    return results

但是在调用 match_asian_cities() 时我得到 SyntaxError: invalid syntax

SyntaxError: invalid syntax (Temp/ipykernel_5228/716370306.py, line 20)
  File "C:\Users\LENOVO\AppData\Local\Temp/ipykernel_5228/716370306.py", line 20
    match city:
          ^
SyntaxError: invalid syntax

Need help to fix this. Thanks!

下面的怎么样

import typing

class City(typing.NamedTuple):
    continent: str
    name: str
    country: str


cities = [
    City('Asia', 'Tokyo', 'JP'),
    City('Asia', 'Delhi', 'IN'),
    City('North America', 'Mexico City', 'MX'),
    City('North America', 'New York', 'US'),
    City('South America', 'São Paulo', 'BR'),
]

asian = [c for c in cities if c.continent == 'Asia']
print(asian)

输出

[City(continent='Asia', name='Tokyo', country='JP'), City(continent='Asia', name='Delhi', country='IN')]

match 功能在 python 3.10.0rc1 中引入。如果此版本的 python 在您的系统中可用,那么您可以尝试一下。所以,现在您可以尝试以下代码片段。

代码:

import typing

class City(typing.NamedTuple):
    continent: str
    name: str
    country: str


def match_asian_cities(cities):
    results = [city for city in cities if city.continent == 'Asia']
    return results

cities = [
    City('Asia', 'Tokyo', 'JP'),
    City('Asia', 'Delhi', 'IN'),
    City('North America', 'Mexico City', 'MX'),
    City('North America', 'New York', 'US'),
    City('South America', 'São Paulo', 'BR'),
]

print(match_asian_cities(cities))

输出:

[City(continent='Asia', name='Tokyo', country='JP'), City(continent='Asia', name='Delhi', country='IN')]