迭代字典中的key和value
2017-01-07 00:35
375 查看
字典是python中十分重要的一个内容。
今天我们来谈谈,在一个 for 循环中,能否同时迭代 key和value?当然可以咯。
dict 对象的 items() 方法返回的值:
items() 方法把dict对象转换成了包含tuple的list,我们对这个list进行迭代,可以同时获得key和value:
和 values() 有一个 itervalues() 类似, items() 也有一个对应的 iteritems(),iteritems() 不把dict转换成list,而是在迭代过程中不断给出 tuple,所以, iteritems() 不占用额外的内存
我们接下来实现一个复杂一些的需求:
请根据dict:
打印出 name : score,最后再打印出平均分 average : score。
我们可以这样实现:
或者:
今天我们来谈谈,在一个 for 循环中,能否同时迭代 key和value?当然可以咯。
dict 对象的 items() 方法返回的值:
>>> d = { 'Adam': 95, 'Lisa': 85, 'Bart': 59 } >>> print d.items() [('Lisa', 85), ('Adam', 95), ('Bart', 59)] >>> for key,value in d.items(): print key,':',value
items() 方法把dict对象转换成了包含tuple的list,我们对这个list进行迭代,可以同时获得key和value:
Lisa : 85 Adam : 95 Bart : 59 >>>
和 values() 有一个 itervalues() 类似, items() 也有一个对应的 iteritems(),iteritems() 不把dict转换成list,而是在迭代过程中不断给出 tuple,所以, iteritems() 不占用额外的内存
我们接下来实现一个复杂一些的需求:
请根据dict:
d = { 'Adam': 95, 'Lisa': 85, 'Bart': 59, 'Paul': 74 }
打印出 name : score,最后再打印出平均分 average : score。
我们可以这样实现:
d = { 'Adam': 95, 'Lisa': 85, 'Bart': 59, 'Paul': 74 } for key, value in d.iteritems(): print "%s : %d" % (key,value) L=(sum(d.itervalues())/float(len(d))) print '%.2f'%L
或者:
d = { 'Adam': 95, 'Lisa': 85, 'Bart': 59, 'Paul': 74 } sum=0.0 for k,v in d.items(): sum+=v print k,':',v print 'average',':',sum/len(d)
相关文章推荐
- 迭代字典中的key和value
- iOS自动签名打包(xcodebuild)----常用
- ArrayList<String>转 CharSequence[]
- Odoo的ir.values
- Wordpress 安装Plugin是报错“To perform the requested action, WordPress needs to access your web server”
- Retrofit学习教程(4)-Multiple Query Parameters of Same Name
- [leetcode]406. Queue Reconstruction by Height
- jfinal最快整合ueditor
- Android UI 美化
- HDU 3530 Subsequence 单调栈应用
- Vue-Router 页面正在加载特效
- 安装rpcbind出错
- [APUE]进程控制(上)
- 如何关闭MIUI新版本中加入的“system锁”校验!
- Distinct Subsequences
- UE4打包问题
- Qt Widgets、QML、Qt Quick的区别
- Debugging performance issues in Go programs
- 初识QML
- execute、executeQuery和executeUpdate之间的区别