如何截斷給定長度的 Python 字典?
要截斷給定長度的 Python 字典,請使用 itertools 模組。此模組實現了許多受 APL、Haskell 和 SML 中構造啟發的迭代器構建塊。對於截斷到給定長度,我們將使用 itertools 模組的 islice() 方法。
該模組標準化了一組核心快速、記憶體高效的工具,這些工具本身或組合使用都很有用。它們共同形成了一個迭代器代數,使得能夠用純 Python 簡潔高效地構建專門的工具。
語法
以下是語法 -
itertools.islice(sequence, stop) or itertools.islice(sequence, start, stop, step)
上面,sequence 引數是要迭代的專案,而 stop 是在特定位置停止迭代。start 是迭代開始的地方。step 有助於跳過專案。islice() 不支援 start、stop 或 step 的負值。
截斷給定長度的字典
我們將使用 itertools 模組的 islice() 方法將具有四個鍵值對的字典截斷為兩個。專案被截斷為兩個,與我們設定的引數相同 -
示例
import itertools # Creating a Dictionary with 4 key-value pairs myprod = { "Product":"Mobile", "Model": "XUT", "Units": 120, "Available": "Yes" } # Displaying the Dictionary print("Dictionary =\n",myprod) # Truncating a Dictionary using the islice() myprod = dict(itertools.islice(myprod.items(),2)) # Displaying the Dictionary print("Dictionary after truncating =\n",myprod)
輸出
Dictionary =
{'Product': 'Mobile', 'Model': 'XUT', 'Units': 120, 'Available': 'Yes'}
Dictionary after truncating =
{'Product': 'Mobile', 'Model': 'XUT'}
在給定範圍內截斷字典
我們將使用 itertools 模組的 islice() 方法截斷具有六個鍵值對的字典。由於我們設定了 start 和 stop 引數,因此專案在範圍內被截斷 -
示例
import itertools # Creating a Dictionary with 6 key-value pairs myprod = { "Product":"Mobile", "Model": "XUT", "Units": 120, "Available": "Yes", "Grade": "A", "Rating": "5" } # Displaying the Dictionary print("Dictionary =\n",myprod) # Truncating a Dictionary using the islice() # We have set the parameters start and stop to truncate in a range myprod = dict(itertools.islice(myprod.items(),3,5)) # Displaying the Dictionary print("Dictionary after truncating =\n",myprod)
輸出
Dictionary =
{'Product': 'Mobile', 'Model': 'XUT', 'Units': 120, 'Available': 'Yes', 'Grade': 'A', 'Rating': '5'}
Dictionary after truncating =
{'Available': 'Yes', 'Grade': 'A'}
透過跳過專案截斷字典
我們將使用 itertools 模組的 islice() 方法截斷具有六個鍵值對的字典。由於我們設定了start 和stop 引數,因此專案在範圍內被截斷。專案使用step 引數跳過 -
示例
import itertools # Creating a Dictionary with 6 key-value pairs myprod = { "Product":"Mobile", "Model": "XUT", "Units": 120, "Available": "Yes", "Grade": "A", "Rating": "5" } # Displaying the Dictionary print("Dictionary =\n",myprod) # Truncating a Dictionary using the islice() # We have set the parameters start, stop and step to skip items myprod = dict(itertools.islice(myprod.items(),2,5,2)) # Displaying the Dictionary print("Dictionary after truncating =\n",myprod)
輸出
Dictionary =
{'Product': 'Mobile', 'Model': 'XUT', 'Units': 120, 'Available': 'Yes', 'Grade': 'A', 'Rating': '5'}
Dictionary after truncating =
{'Units': 120, 'Grade': 'A'}
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP