方法一、
程序
# -*- coding: utf-8 -*-
'''
功能:用两种方法将单词按首字母分类(1)
作者:雾爱
日期:2021年12月9日
'''
words = ['apple','book','but','hat','at','better','love',
'cute','mood','lucy','protcet','help','invironment']
map = {
}
for word in words:
start_letter = word[0]
if start_letter not in map:
map[start_letter] = [word]
else:
map[start_letter].append(word)
print(map)
for key in map.keys():
print('{}:{}'.format(key,map[key]))
查看结果
方法二、
程序
# -*- coding: utf-8 -*-
'''
功能:用两种方法将单词按首字母分类(2)
作者:雾爱
日期:2021年12月9日
'''
words = ['apple','book','but','hat','at','better','love',
'cute','mood','lucy','protcet','help','invironment']
map = {
}
for word in words:
start_letter = word[0]
map.setdefault(start_letter,[]).append(word)
print(map)
for key in map.keys():
print('{}:{}'.format(key,map[key]))
查看结果
两种方法最后的结果都是一样的,就看你喜欢哪一种了