首頁  >  文章  >  後端開發  >  Python中items()系列函數的用法詳解

Python中items()系列函數的用法詳解

Y2J
Y2J原創
2017-05-17 15:11:3714309瀏覽

這篇文章主要介紹了Python中dictionary items()系列函數的用法,很實用的函數,需要的朋友可以參考下

本文實例講述了Python中dictionary items()系列函數的用法,對Python程式設計有很好的參考借鏡價值。具體分析如下:

先來看一個範例:

import html  # available only in Python 3.x 
def make_elements(name, value, **attrs): 
  keyvals = [' %s="%s"' % item for item in attrs.items()] 
  attr_str = ''.join(keyvals) 
  element = &#39;<{name}{attrs}>{value}</{name}>&#39;.format( 
      name = name, 
      attrs = attr_str, 
      value = html.escape(value)) 
  return element 
make_elements(&#39;item&#39;, &#39;Albatross&#39;, size=&#39;large&#39;, quantity=6) 
make_elements(&#39;p&#39;, &#39;<spam>&#39;)

這個程式的作用很簡單,就是產生HTML標籤,注意html這個模組只能在Python 3 .x才有。

起初我只是注意到,產生標籤屬性列表的keyvals這個dictionary類型變數建構的方式很有意思,兩個%s對應一個item,所以就查閱了相關的資料,結果扯出了挺多的東西,在此一併總結。

註:下面所有Python解釋器使用的版本,2.x 對應的是2.7.3,3.x 對應的是3.4.1
在Python 2.x 裡,官方文件裡items的方法是這麼說明:產生一個(key, value) 對的list,就像下面這樣:

>>> d = {&#39;size&#39;: &#39;large&#39;, &#39;quantity&#39;: 6} 
>>> d.items() 
[(&#39;quantity&#39;, 6), (&#39;size&#39;, &#39;large&#39;)]

搜尋的過程中,無意看到stackoverflow上這樣一個問題: dict.items()和dict.iteritems()有什麼差別? ,第一個答案大致的意思是這樣的:

「起初items() 就是返回一個像上面那樣的包含dict所有元素的list,但是由於這樣太浪費內存,所以後來就加入了(註:在Python 2.2開始出現的)iteritems(), iterkeys(), itervalues()這一組函數,用於返回一個iterator 來節省內存,但是在3.x 裡items() 本身就返回這樣的iterator,所以在3.x 裡items() 的行為和2.x 的iteritems() 行為一致,iteritems()這一組函數就廢除了。是,這個答案雖然被採納,下面的評論卻指出,這種說法並不准確,在3.x 裡items() 的行為和2.x 的iteritems() 不一樣,它實際上返回的是一個" full sequence-protocol

object

",這個物件能夠反映出dict 的變化,後來在Python 2.7 裡面也加入了另外一個函數viewitems() 和3.x 的這種行為保持一致為了證實評論中的說法,我做了下面的測試,注意觀察測試中使用的Python版本:
測試1(Python 2.7.3):

Python 2.7.3 (default, Feb 27 2014, 19:58:35)  
[GCC 4.6.3] on linux2 
Type "help", "copyright", "credits" or "license" for more information. 
>>> d = {&#39;size&#39;: &#39;large&#39;, &#39;quantity&#39;: 6} 
>>> il = d.items() 
>>> it = d.iteritems() 
>>> vi = d.viewitems() 
>>> il 
[(&#39;quantity&#39;, 6), (&#39;size&#39;, &#39;large&#39;)] 
>>> it 
<dictionary-itemiterator object at 0x7fe555159f18> 
>>> vi 
dict_items([(&#39;quantity&#39;, 6), (&#39;size&#39;, &#39;large&#39;)])

測試2(Python 3.4.1):

Python 3.4.1 (default, Aug 12 2014, 16:43:01)  
[GCC 4.9.0] on linux 
Type "help", "copyright", "credits" or "license" for more information. 
>>> d = {&#39;size&#39;: &#39;large&#39;, &#39;quantity&#39;: 6} 
>>> il = d.items() 
>>> it = d.iteritems() 
Traceback (most recent call last): 
 File "<stdin>", line 1, in <module> 
AttributeError: &#39;dict&#39; object has no attribute &#39;iteritems&#39; 
>>> vi = d.viewitems() 
Traceback (most recent call last): 
 File "<stdin>", line 1, in <module> 
AttributeError: &#39;dict&#39; object has no attribute &#39;viewitems&#39; 
>>> il 
dict_items([(&#39;size&#39;, &#39;large&#39;), (&#39;quantity&#39;, 6)])

可以看到在Python 3.x 裡面,iteritems() 和viewitems() 這兩個方法都已經廢除了,而item() 得到的結果是和2.x 裡面viewitems() 一致的。

2.x 裡 iteritems() 和 viewitems() 回傳的內容都是可以用 for 來遍歷的,像下面這樣

>>> for k, v in it: 
...  print k, v 
...  
quantity 6 
size large 
>>> for k, v in vi: 
...  print k, v 
...  
quantity 6 
size large

這兩者的區別體現在哪裡呢? viewitems() 回傳的是view object,它可以反映出dictionary 的變化,例如上面的例子,假如在使用it 和vi 這兩個變數之前,向d 裡面加上一個key-value組合,差別就很容易看出來了。

>>> it = d.iteritems() 
>>> vi = d.viewitems() 
>>> d[&#39;newkey&#39;] = &#39;newvalue&#39; 
>>> d 
{&#39;newkey&#39;: &#39;newvalue&#39;, &#39;quantity&#39;: 6, &#39;size&#39;: &#39;large&#39;} 
>>> vi 
dict_items([(&#39;newkey&#39;, &#39;newvalue&#39;), (&#39;quantity&#39;, 6), (&#39;size&#39;, &#39;large&#39;)]) 
>>> it 
<dictionary-itemiterator object at 0x7f50ab898f70> 
>>> for k, v in vi: 
...  print k, v 
...  
newkey newvalue 
quantity 6 
size large 
>>> for k, v in it: 
...  print k, v 
...  
Traceback (most recent call last): 
 File "<stdin>", line 1, in <module> 
RuntimeError: dictionary changed size during iteration

在第三行中,我們像d 裡面插入了一個新的元素,vi 可以繼續遍歷,而且新的遍歷能夠反映出d 的變化,但是在遍歷it 的時候,報錯提示dictionary在遍歷的時候大小發生了變化,遍歷失敗。

總結起來,在2.x 裡面,最初是items() 這個方法,但是由於太浪費內存,所以加入了iteritems() 方法,用於返回一個iterator,在3.x 裡面將items () 的行為修改成回傳一個view object,讓它回傳的物件同樣也可以反映出原dictionary 的變化,同時在2.7 裡面又加入了viewitems() 向下相容這個特性。

所以在 3.x 裡面不需要再去糾結於三者的不同之處,因為只保留了一個 items() 方法。


相信本文所述範例對大家的Python程式設計有一定的借鏡價值。

【相關推薦】

1.

特別推薦#:「php程式設計師工具箱」V0.1版本下載2.

Python免費影片教學

3. 

Python基礎入門之items()方法

4. Python中的item()函數遍歷字典的實例

#5. 介紹三種存取字典的方法

6. 在sorted中iteriitems和items不同之處

以上是Python中items()系列函數的用法詳解的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn