这篇教程Python字典中items()函数案例详解写得很实用,希望能帮到您。 Python3:字典中的items()函数一、Python2.x中items(): 和之前一样,本渣渣先贴出来python中help的帮助信息: >>> help(dict.items)Help on method_descriptor:items(...) D.items() -> list of D's (key, value) pairs, as 2-tuples >>> help(dict.iteritems)Help on method_descriptor:iteritems(...) D.iteritems() -> an iterator over the (key, value) items of D >>> help(dict.viewitems)Help on method_descriptor:viewitems(...) D.viewitems() -> a set-like object providing a view on D's items 在Python2.x中,items( )用于 返回一个字典的拷贝列表【Returns a copy of the list of all items (key/value pairs) in D】,占额外的内存。 iteritems() 用于返回本身字典列表操作后的迭代【Returns an iterator on all items(key/value pairs) in D】,不占用额外的内存。 >>> d={1:'one',2:'two',3:'three'}>>> type(d.items())<type 'list'>>>> type(d.iteritems())<type 'dictionary-itemiterator'>>>> type(d.viewitems())<type 'dict_items'> 二、Python3.x中items():>>> help(dict.items)Help on method_descriptor:items(...) D.items() -> a set-like object providing a view on D's items Python 3.x 里面,iteritems() 和 viewitems() 这两个方法都已经废除了,而 items() 得到的结果是和 2.x 里面 viewitems() 一致的。在3.x 里 用 items()替换iteritems() ,可以用于 for 来循环遍历。 >>> d={1:'one',2:'two',3:'three'}>>> type(d.items())<class 'dict_items'> 简单的例子: d = { 'Adam': 95, 'Lisa': 85, 'Bart': 59, 'Paul': 74 }sum = 0for key, value in d.items(): sum = sum + value print(key, ':' ,value)print('平均分为:' ,sum /len(d)) 输出结果: D:/Users/WordZzzz/Desktop>python3 test.py Adam : 95 Lisa : 85 Bart : 59 Paul : 74 平均分为:78.25
到此这篇关于Python字典中items()函数案例详解的文章就介绍到这了,更多相关Python字典中items()函数内容请搜索51zixue.net以前的文章或继续浏览下面的相关文章希望大家以后多多支持51zixue.net! Python中的super()面向对象编程 Python批量处理工作簿和工作表的实现示例 |