python - 从列表中填充字典的最快方法?
问题描述
这是我的清单:
animallist=["bird","cow","chicken","horse"]
我想创建一个字典,将这些动物作为由 some_funtion 确定的键和值。我的脚本:
def some_function(eachanimal):
#do some stuff with the entry, for example:
return eachanimal+"_value"
animallist=["bird","cow","chicken","horse"]
mydict={}
for eachanimal in animallist:
mydict[eachanimal]=some_function(eachanimal)
这会创建 mydict,即:
{'bird': 'bird_value',
'cow': 'cow_value',
'chicken': 'chicken_value',
'horse': 'horse_value'}
我怎样才能更快或更紧凑地做到这一点?
解决方案
我很确定它不会更快,但我发现它至少更优雅
mydict = {x: some_function(x) for x in animallist}
推荐阅读
- java - 如何处理列表整数列表并查找邻居?
- node.js - 为什么在 NodeJS 中使用“require”时会出现如此奇怪的行为?
- asp.net-mvc - Visual Studio 2019 for Mac:“当前上下文中不存在名称布局”
- python - 两个字符串匹配多少百分比?
- node.js - 间隔发送消息,然后将其删除
- networking - 有没有办法给电脑分配一个公共IP?
- unicode - 创建一个日志文件,我应该选择哪种格式?
- google-apps-script - Gmail AppScript mailMessage.getFrom() 返回电子邮件而不是名称
- intellij-idea - Intellij IDEA 插件检查块构建
- git - 能够通过 CMD/git bash 连接到私有 SSH 服务器,但无法 git clone、git push 或 git pull