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

时间:2021-11-29 20:27:18

List.

名单。

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

Result.

结果。

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

I can make it work like this.

我可以让它像这样工作。

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)

It is probably a bit faster to pre-populate the dictionary with A-Z, to save the key check on every name, and then afterwards delete keys with empty lists. I'm not sure either is the best solution though.

使用A-Z预先填充字典可能要快一点,以保存每个名称的密钥检查,然后删除带有空列表的密钥。我不确定要么是最好的解决方案。

Is there a pythonic way to do this?

有没有pythonic方式来做到这一点?

2 个解决方案

#1


9  

Anything wrong with this? I agree with Antoine, the oneliner solution is rather cryptic.

这有什么不对吗?我同意Antoine,oneliner解决方案相当神秘。

import collections

alphabet = collections.defaultdict(list)
for word in words:
    alphabet[word[0].upper()].append(word)

#2


5  

I don't know if it's Pythonic, but it's more succinct:

我不知道它是否是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))

EDIT 2 made it less succinct than previous version, more readable and more correct (groupby works as intended only on sorted lists)

编辑2使它不如以前的版本简洁,更可读和更正确(groupby只在排序列表上工作)

#1


9  

Anything wrong with this? I agree with Antoine, the oneliner solution is rather cryptic.

这有什么不对吗?我同意Antoine,oneliner解决方案相当神秘。

import collections

alphabet = collections.defaultdict(list)
for word in words:
    alphabet[word[0].upper()].append(word)

#2


5  

I don't know if it's Pythonic, but it's more succinct:

我不知道它是否是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))

EDIT 2 made it less succinct than previous version, more readable and more correct (groupby works as intended only on sorted lists)

编辑2使它不如以前的版本简洁,更可读和更正确(groupby只在排序列表上工作)