如何截断给定长度的 Python 字典?

programmingpythonserver side programming

要截断给定长度的 Python 字典,请使用 itertools 模块。此模块实现了许多迭代器构建块,这些构建块受到 APL、Haskell 和 SML 构造的启发。要截断给定长度,我们将使用 itertools 模块的 islice() 方法。

该模块标准化了一组快速、内存高效的核心工具,这些工具可以单独使用或组合使用。它们一起构成了一个迭代器代数,使得在纯 Python 中简洁高效地构建专用工具成为可能。

语法

语法如下 -

itertools.islice(sequence, stop)
或
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() 方法截断具有六个键值对的字典。由于我们已设置开始和停止参数,因此项目在范围内被截断 −

示例

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() 方法截断具有六个键值对的字典。由于我们设置了 startstop 参数,因此项目在一定范围内被截断。使用 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'}

相关文章