在下面的字典中,可以根据键中的最后一个前缀对元素进行排序
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
谢谢..
答案 0 :(得分:-1)
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