【问题标题】:Pattern matching find pattern anywhere in list模式匹配在列表中的任意位置查找模式
【发布时间】:2022-01-02 15:07:56
【问题描述】:

我有以下字典,如果"status""progress",我想获得"msg" 的值。状态"progress" 或键"msg" 可能在字典中也可能不在字典中,这就是为什么我想到使用模式匹配来查看是否能得到我想要的。

我的尝试

my_dict = {
    "outer": [
        {"status": "to do", "desc": [{"msg": "foo"}]},
        {"status": "progress", "desc": [{"msg": "bar"}]},
        {"status": "done", "desc": [{"msg": "baz"}]},
    ]
}

match my_dict:
    case {'outer': [{'status': 'progress', 'desc': [{'msg': x}]}]}:
        print(x)

我正在寻找类似case {'outer': [*_, {'status': 'progress', 'desc': [{'msg': x}]}, *_]}: 的东西,但这不起作用SyntaxError: multiple starred names in sequence pattern

我想要的输出(使用模式匹配)

bar

我可以通过以下方式获得我想要的东西,但我需要做一些检查以确保密钥存在。

for i in my_dict['outer']: # check every status
    if i['status'] == 'progress': # check if the status is "progress"
        if 'desc' in i:
            for j in i['desc']: # loop the values of "desc"
                if 'msg' in j: # if the msg is there get the value
                    x = j['msg']

出于好奇,我想知道是否有办法使用模式匹配来解决这个问题。

【问题讨论】:

    标签: python pattern-matching python-3.10


    【解决方案1】:

    我猜你可以做到以下几点:

    for info in my_dict["outer"]:
        match info:
            case {"status": "progress", "desc": [{"msg": msg}]}:
                print(msg)
                break
    else:
        print("No Match")
    

    【讨论】:

    • 这看起来很简单,但可以满足我的需求,如果我没有其他更好的解决方案,我会接受,(我怀疑它会比这更简单)
    【解决方案2】:

    如果保证progress的值在my_dict['outer']中只出现一次,那么你可以在匹配前对列表项进行预过滤:

    my_dict = {'outer': [{'status': 'to do', 'desc': [{'msg': 'foo'}]}, {'status': 'progress', 'desc': [{'msg': 'bar'}]}, {'status': 'done', 'desc': [{'msg': 'baz'}]}]}
    match [i for i in my_dict['outer'] if i['status'] == 'progress']:
       case [{'status': _, 'desc': [{'msg': msg}]}]:
          print(msg)
    

    输出:

    'bar'
    

    【讨论】:

      猜你喜欢
      • 2013-01-08
      • 1970-01-01
      • 2023-04-03
      • 1970-01-01
      • 1970-01-01
      • 2014-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多