在Python中将名称列表拆分为字母字典
发布时间:2020-12-20 12:37:29  所属栏目:Python  来源:网络整理 
            导读:名单. ['Chrome','Chromium','Google','Python'] 结果. {'C': ['Chrome','Chromium'],'G': ['Google'],'P': ['Python']} 我可以让它像这样工作. alphabet = dict()for name in ['Chrome','Python']: character = name[:1].upper() if not character in alpha
                
                
                
            | 
                         
 名单. 
  
  
  
['Chrome','Chromium','Google','Python'] 结果. {'C': ['Chrome','Chromium'],'G': ['Google'],'P': ['Python']} 
 我可以让它像这样工作. alphabet = dict()
for name in ['Chrome','Python']:
  character = name[:1].upper()
  if not character in alphabet:
    alphabet[character] = list()
  alphabet[character].append(name) 
 使用A-Z预先填充字典可能要快一些,以保存每个名称的密钥检查,然后删除带有空列表的密钥.我不确定这两者是不是最好的解决方案. 有没有pythonic方式来做到这一点? 解决方法
 这有什么不对吗?我同意Antoine,oneliner解决方案相当神秘. 
  
  
  
        import collections
alphabet = collections.defaultdict(list)
for word in words:
    alphabet[word[0].upper()].append(word)
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!  | 
                  
