在數學笛卡爾乘積的術語中,將兩個集合定義為所有有序對(a,b)的集合,其中a屬於A,b屬於B。為更好地理解,請考慮以下示例。
例子:
Input: arr1 = [1, 2, 3]
arr2 = [5, 6, 7]
Output: [(1, 5), (1, 6), (1, 7), (2, 5), (2, 6), (2, 7), (3, 5), (3, 6), (3, 7)]
Input: arr1 = [10, 12]
arr2 = [8, 9, 10]
Output: [(10, 8), (10, 9), (10, 10), (12, 8), (12, 9), (12, 10)]
可以通過循環來完成上述解決方案,但是我們將使用特殊的Python庫itertools.product()查找笛卡爾積。讓我們看一下這個Python庫的工作和用例。
Python中的Itertools是什麽?
Python Itertools是Python中的一個庫,其中包含多種方法,這些方法在各種迭代器中用於計算快速且代碼高效的解決方案。
itertools.product() falls under the category called Combinatoric iterators of the Python itertools library.
注意:有關更多信息,請參閱Python Itertools。
itertools.product()是做什麽的?
itertools.product()
用於從給定的迭代器中找到笛卡爾積,輸出按字典順序排序。 itertools.product()可以兩種不同的方式使用:
- itertools.product(*iterables, repeat=1):
它以可選關鍵字“repeat”指定的次數返回所提供的iterable的笛卡爾積。例如,product(arr,repeat = 3)表示與product(arr,arr,arr)相同。 - itertools.product(*iterables):
它返回所有可迭代的笛卡爾乘積作為參數。例如,product(arr1,arr2,arr3)。
例:
from itertools import product
def cartesian_product(arr1, arr2):
# return the list of all the computed tuple
# using the product() method
return list(product(arr1, arr2))
# Driver Function
if __name__ == "__main__":
arr1 = [1, 2, 3]
arr2 = [5, 6, 7]
print(cartesian_product(arr1, arr2))
輸出:
[(1, 5), (1, 6), (1, 7), (2, 5), (2, 6), (2, 7), (3, 5), (3, 6), (3, 7)]
注:本文由純淨天空篩選整理自anubhavraj_08大神的英文原創作品 Python – Itertools.Product()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。