本网站可以出售:只需60000元直接拥有。QQ:939804642
您当前的位置:首页 > IT编程 > python
| C语言 | Java | VB | VC | python | Android | TensorFlow | C++ | oracle | 学术与代码 | cnn卷积神经网络 | gnn | 图像修复 | Keras | 数据集 | Neo4j | 自然语言处理 | 深度学习 | 医学CAD | 医学影像 | 超参数 | pointnet | pytorch | 异常检测 | Transformers | 情感分类 | 知识图谱 |

自学教程:Python字典中items()函数案例详解

51自学网 2021-10-30 22:13:55
  python
这篇教程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批量处理工作簿和工作表的实现示例
51自学网自学EXCEL、自学PS、自学CAD、自学C语言、自学css3实例,是一个通过网络自主学习工作技能的自学平台,网友喜欢的软件自学网站。
京ICP备13026421号-1