Python 程式使用 itertools.product 處理列表的列表中的元素


itertools 是 Python 標準庫中的一個模組,它提供了一系列用於高效迭代和組合可迭代物件的工具,並且它是 Python 標準庫的一部分,因此無需執行任何其他安裝。它提供了各種功能,可用於以不同方式操作、組合和迭代可迭代物件。

itertools.product() 函式與itertools 模組相關,它是生成多個可迭代物件的笛卡爾積的強大工具。它接受一個或多個可迭代物件作為輸入,並返回一個迭代器,該迭代器生成表示輸入可迭代物件中所有可能元素組合的元組。

itertools.product 返回一個迭代器;換句話說,它在需要時動態生成元組。這在處理大型輸入可迭代物件或組合數量巨大時非常節省記憶體。

語法

使用itertools.product() 函式的語法如下:

itertools.product(*iterables, repeat=1)

其中,

  • 可迭代物件是組合以生成笛卡爾積的一個或多個元素。

  • repeat 是一個整數值,指定輸入可迭代物件中每個元素應重複的次數。

示例

在此示例中,我們使用itertools.product() 生成顏色和尺寸的所有可能組合。生成的迭代器 product 包含表示每個組合的元組,我們遍歷它以列印每個元組。

import itertools
colors = ['red', 'green', 'blue']
sizes = ['S', 'M', 'L']
product = itertools.product(colors, sizes)
for item in product:
   print(item)

輸出

('red', 'S')
('red', 'M')
('red', 'L')
('green', 'S')
('green', 'M')
('green', 'L')
('blue', 'S')
('blue', 'M')
('blue', 'L')

示例

在此示例中,我們嘗試使用itertools.product() 函式計算字母和數字列表的笛卡爾積,然後生成的迭代器生成包含字母列表中一個元素和數字列表中一個元素的所有可能組合的元組。然後使用迴圈列印這些元組。

import itertools
letters = ['a', 'b']
numbers = [1, 2, 3]
result = itertools.product(letters, numbers)
for item in result:
   print(item)

輸出

('a', 1)
('a', 2)
('a', 3)
('b', 1)
('b', 2)
('b', 3)

示例

在前面的示例中,我們計算了數字和字母的笛卡爾積,重複次數為一次。在此示例中,repeat 引數設定為 3,這會導致笛卡爾積重複三次,生成的迭代器生成包含數字列表中三個元素的所有可能組合(包括重複)的元組。

import itertools
letters = ['a', 'b']
numbers = [1, 2, 3]
result = itertools.product(letters, numbers, repeat = 2)
for item in result:
   print(item)

輸出

('a', 1, 'a', 1)
('a', 1, 'a', 2)
('a', 1, 'a', 3)
('a', 1, 'b', 1)
('a', 1, 'b', 2)
('a', 1, 'b', 3)
('a', 2, 'a', 1)
('a', 2, 'a', 2)
('a', 2, 'a', 3)
('a', 2, 'b', 1)
('a', 2, 'b', 2)
('a', 2, 'b', 3)
('a', 3, 'a', 1)
('a', 3, 'a', 2)
('a', 3, 'a', 3)
('a', 3, 'b', 1)
('a', 3, 'b', 2)
('a', 3, 'b', 3)
('b', 1, 'a', 1)
('b', 1, 'a', 2)
('b', 1, 'a', 3)
('b', 1, 'b', 1)
('b', 1, 'b', 2)
('b', 1, 'b', 3)
('b', 2, 'a', 1)
('b', 2, 'a', 2)
('b', 2, 'a', 3)
('b', 2, 'b', 1)
('b', 2, 'b', 2)
('b', 2, 'b', 3)
('b', 3, 'a', 1)
('b', 3, 'a', 2)
('b', 3, 'a', 3)
('b', 3, 'b', 1)
('b', 3, 'b', 2)
('b', 3, 'b', 3)

更新於: 2023年8月2日

233 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告