代码之家  ›  专栏  ›  技术社区  ›  user479870

在Python中将名称列表拆分为字母字典

  •  3
  • user479870  · 技术社区  · 15 年前

    列表。

    ['Chrome', 'Chromium', 'Google', 'Python']
    

    {'C': ['Chrome', 'Chromium'], 'G': ['Google'], 'P': ['Python']}
    

    我可以这样做。

    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)
    

    用a-Z预先填充字典、保存对每个名称的键检查,然后用空列表删除键,可能要快一点。不过,我也不确定这是否是最好的解决办法。

    有没有 蟒蛇 怎么做?

    2 回复  |  直到 12 年前
        1
  •  9
  •   user395760 user395760    15 年前

    这有什么问题吗?我同意安托万的观点,一行解决方案相当隐晦。

    import collections
    
    alphabet = collections.defaultdict(list)
    for word in words:
        alphabet[word[0].upper()].append(word)
    
        2
  •  5
  •   Amnon    15 年前

    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))
    

    编辑2 使它比以前的版本更简洁,更可读,更正确( groupby 仅适用于排序列表)