为了账号安全,请及时绑定邮箱和手机立即绑定

从列表中填充字典的最快方法?

从列表中填充字典的最快方法?

临摹微笑 2021-06-07 15:29:45
这是我的清单: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'}我怎样才能更快或更紧凑地做到这一点?
查看完整描述

3 回答

?
子衿沉夜

TA贡献1828条经验 获得超3个赞

我很确定它不会更快,但我发现它至少更优雅

mydict = {x: some_function(x) for x in animallist}


查看完整回答
反对 回复 2021-06-09
  • 3 回答
  • 0 关注
  • 153 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号