strLst = [‘Insert’, ‘key’,‘with’,‘a’,‘value’,‘of’,‘default’,‘if’,‘key’,‘is’,‘not’,‘in’,‘the’,‘dictionary’]
strLst.sort()
d={}
for word in strLst:
d.setdefault(len(word), []).append(word) #Insert key with a value of default if key is not in the dictionary.
for key in sorted(d):
print ("%s: %s" % (key, d[key]))
输出结果:
1: [‘a’]
2: [‘if’, ‘in’, ‘is’, ‘of’]
3: [‘key’, ‘key’, ‘not’, ‘the’]
4: [‘with’]
5: [‘value’]
6: [‘Insert’]
7: [‘default’]
10: [‘dictionary’]
字典默认值设置与排序
本文介绍了一种使用Python处理字符串列表的方法,通过设置字典的默认值并进行排序来整理数据。此方法适用于需要根据单词长度进行归类的应用场景。
772

被折叠的 条评论
为什么被折叠?



