Pyhton学习 Python3:字典中的items()函数 Python3:字典中的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
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
>>> help(dict.iteritems)
Help on method_descriptor:

iteritems(...)
    D.iteritems() -> an iterator over the (key, value) items of D
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
>>> help(dict.viewitems)
Help on method_descriptor:

viewitems(...)
    D.viewitems() -> a set-like object providing a view on D's items
  
  
  • 1
  • 2
  • 3
  • 4
  • 5

  在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'>
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

二、Python3.x中items():

>>> help(dict.items)
Help on method_descriptor:

items(...)
    D.items() -> a set-like object providing a view on D's items
  
  
  • 1
  • 2
  • 3
  • 4
  • 5

  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'>
  
  
  • 1
  • 2
  • 3

简单的例子:

d = { 'Adam': 95, 'Lisa': 85, 'Bart': 59, 'Paul': 74 }
sum = 0
for key, value in d.items():
    sum = sum + value
    print(key, ':' ,value)
print('平均分为:' ,sum /len(d))
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

输出结果:

D:\Users\WordZzzz\Desktop>python3 test.py
Adam : 95
Lisa : 85
Bart : 59
Paul : 74
平均分为: 78.25
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

关于python3.x中items具体的应用,可以通过下面的传送门到达机器学习实战中找到:

系列教程持续发布中,欢迎订阅、关注、收藏、评论、点赞哦~~( ̄▽ ̄~)~

完的汪(∪。∪)。。。zzz

				<script>
					(function(){
						function setArticleH(btnReadmore,posi){
							var winH = $(window).height();
							var articleBox = $("div.article_content");
							var artH = articleBox.height();
							if(artH > winH*posi){
								articleBox.css({
									'height':winH*posi+'px',
									'overflow':'hidden'
								})
								btnReadmore.click(function(){
									articleBox.removeAttr("style");
									$(this).parent().remove();
								})
							}else{
								btnReadmore.parent().remove();
							}
						}
						var btnReadmore = $("#btn-readmore");
						if(btnReadmore.length>0){
							if(currentUserName){
								setArticleH(btnReadmore,3);
							}else{
								setArticleH(btnReadmore,1.2);
							}
						}
					})()
				</script>
				</article>

猜你喜欢

转载自blog.csdn.net/zjc910997316/article/details/82944538