名单.
['Chrome', 'Chromium', 'Google', 'Python']
Run Code Online (Sandbox Code Playgroud)
结果.
{'C': ['Chrome', 'Chromium'], 'G': ['Google'], 'P': ['Python']}
Run Code Online (Sandbox Code Playgroud)
我可以让它像这样工作.
alphabet = dict()
for name in ['Chrome', 'Chromium', 'Google', 'Python']:
character = name[:1].upper()
if not character in alphabet:
alphabet[character] = list()
alphabet[character].append(name)
Run Code Online (Sandbox Code Playgroud)
使用AZ预填充字典可能要快一些,保存每个名称的密钥检查,然后删除带有空列表的密钥.我不确定这两者是不是最好的解决方案.
有没有pythonic方式来做到这一点?
小智 9
这有什么不对吗?我同意Antoine,oneliner解决方案相当神秘.
import collections
alphabet = collections.defaultdict(list)
for word in words:
alphabet[word[0].upper()].append(word)
Run Code Online (Sandbox Code Playgroud)
我不知道它是否是Pythonic,但它更简洁:
import itertools
def keyfunc(x):
return x[:1].upper()
l = ['Chrome', 'Chromium', 'Google', 'Python']
l.sort(key=keyfunc)
dict((key, list(value)) for (key,value) in itertools.groupby(l, keyfunc))
Run Code Online (Sandbox Code Playgroud)
编辑2使它不如以前的版本简洁,更可读和更正确(groupby仅在排序列表上工作)