Python中itertools.product()函数调用

此次刷题过程中接触到Python中itertools包的product函数调用。

product(A,B)用于求可迭代对象A和B的笛卡尔积(后续实例说明),和嵌套的for循环等价,
即product(A,B)>= ((x,y) for x in A for y in B)

首先调用Python包:import itertools

其product函数使用形式为:itertools.product(*iterables,repeat= *)
iterables为可迭代对象,repeat的数值定义iterable重复几次。

A = [1,2,3]
B = [3,4,5]
for item in itertools.product(A,B):
	print(item)

#输出结果为:
(1, 3)
(1, 4)
(1, 5)
(2, 3)
(2, 4)
(2, 5)
(3, 3)
(3, 4)
(3, 5)
可见product函数将每个迭代对象中的每一个元素相互组合起来构成一个元组,并且以列表的形式输出所有组合。
因此在实际应用中,可以取代嵌套循环使用,简化代码块。

你可能感兴趣的:(Python中itertools.product()函数调用)