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

在Python中将名称列表拆分为字母字典,第1张

概述名单. ['Chrome', 'Chromium', 'Google', 'Python'] 结果. {'C': ['Chrome', 'Chromium'], 'G': ['Google'], 'P': ['Python']} 我可以让它像这样工作. alphabet = dict()for name in ['Chrome', 'Chromium', 'Google', '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 Alphabet:    Alphabet[character] = List()  Alphabet[character].append(name)

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

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

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

import collectionsAlphabet = collections.defaultdict(List)for word in words:    Alphabet[word[0].upper()].append(word)
总结

以上是内存溢出为你收集整理的在Python中将名称列表拆分为字母字典全部内容,希望文章能够帮你解决在Python中将名称列表拆分为字母字典所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1195112.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-03
下一篇 2022-06-03

发表评论

登录后才能评论

评论列表(0条)

保存