使用Python在字典中进行模式匹配

1 投票
1 回答
3826 浏览
提问于 2025-04-16 02:21

在下面这个字典中,能不能根据键的最后一个前缀来排序元素呢?

opt_dict=(
{'option1':1,
 'nonoption2':1,
 'nonoption3':12,
 'option4':6,
 'nonoption5':5,
 'option6':1,
 'option7':1,
  })

    for key,val in opt_dict.items():
           if "answer" in key:  //match keys last prefix and print output

               print "found option 1,4,6,7" //in ascending order
           elif "nonanswer" in key: //match keys last prefix and print output
               print "found option 2,3,5 "  //in ascending order

谢谢..

1 个回答

-2
for k,v in sorted(opt_dict.items(),
                  key = lambda item: int(item[0][len("option"):])
                            if item[0].startswith("option")
                            else int(item[0][len("nonoption"):])
                    ):
    print k,v

输出:

option1 1
nonoption2 1
nonoption3 12
option4 6
nonoption5 5
option6 1
option7 1

撰写回答