Python 3 中的模式匹配字典

问题描述 投票:0回答:3

我正在尝试对 python 字典中的元素进行模式匹配,如下所示:

person = {"name": "Steve", "age": 5, "gender": "male"}
{"name": name, "age": age} = person # This line right here
drives = is_driving_age(age)

print f"{name} is {age} years old. He {'can' if drives else 'can\'t'} drive."

# Output: Steve is 5 years old. He can't drive.

有没有办法在Python 3中做这样的事情?我有一个返回相当大字典的函数,我真的很希望能够对数据进行模式匹配,而不是花费 20 行来解构它。

编辑:这里的前几个答案假设我只是想打印出数据,可能我的部分不够清晰。请注意,我不仅仅是试图打印出数据,我还试图将其用于进一步的计算。

python python-3.x dictionary pattern-matching
3个回答
2
投票

这并不是真正的语言功能,但您可以使用解包运算符作为解决方法:

def is_driving_age(age, **_):
    return age > 17
def print_result(drives, name, age, **_):
    print(f"{name} is {age} years old. He {'can' if drives else 'is not allowed to'} drive.")

person = {"name": "Steve", "age": 5, "gender": "male"}

drives = is_driving_age(**person)
print_result(drives, **person)

2
投票
person = {"name": "Steve", "age": 5, "gender": "male"}

my_str = "{name} is {age} years old.".format(**person)

print(my_str)

史蒂夫今年 5 岁了。


0
投票

从 Python 3.10 开始,结构模式匹配现在已成为该语言的一部分!

https://peps.python.org/pep-0636/#going-to-the-cloud-mappings

person = {"name": "Steve", "age": 5, "gender": "male"}
match person:
    case {"name": name, "age": age}:  # This line right here
        drives = is_driving_age(age)
        print(f"{name} is {age} years old. He {'can' if drives else 'can\'t'} drive.")

映射中的额外键将在匹配时被消除,除非您使用

捕获它们
match person:
    case {"name": name, "age": age, **extra}:
        # ...

另请参阅

© www.soinside.com 2019 - 2024. All rights reserved.