欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 财经 > 创投人物 > 【Python】笛卡尔积 intertools.product()

【Python】笛卡尔积 intertools.product()

2024/10/24 11:20:12 来源:https://blog.csdn.net/u010528690/article/details/140929416  浏览:    关键词:【Python】笛卡尔积 intertools.product()

一、题目

This tool computes the cartesian product of input iterables.

It is equivalent to nested for-loops.

For example, product(A, B) returns the same as ((x,y) for x in A fro y in B).

Sample Code

from itertools import productprint(list(product([1,2,3], repeat=2)))print(list(product([1,2,3],[3,4])))A = [[1,2,3],[3,4,5]]
print(list(product(*A))B = [[1,2,3],[3,4,5],[7,8]]
print(list(product(*B)))

>>> [(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3)]
>>> [(1, 3), (1, 4), (2, 3), (2, 4), (3, 3), (3, 4)]
>>> [(1, 3), (1, 4), (2, 3), (2, 4), (3, 3), (3, 4)]
>>> [(1, 3, 7), (1, 3, 8), (1, 4, 7), (1, 4, 8), (1, 5, 7), (1, 5, 8), (2, 3, 7), (2, 3, 8), (2, 4, 7), (2, 4, 8), (2, 5, 7), (2, 5, 8), (3, 3, 7), (3, 3, 8), (3, 4, 7), (3, 4, 8), (3, 5, 7), (3, 5, 8)]

二、代码

from itertools import product
print("Please enter the elements of list A, separated by spaces:")
A = list(map(int, input().split()))
print("Please enter the elements of list B, separated by spaces:")
B = list(map(int, input().split()))cartesian_product = list(product(A, B))
output = ' '.join([f'({a}, {b})' for a, b in cartesian_product])
print(output)
print(*cartesian_product)

输入:

Please enter the elements of list A, separated by spaces:
1 2
Please enter the elements of list B, separated by spaces:
3 4

输出:

(1, 3) (1, 4) (2, 3) (2, 4)
(1, 3) (1, 4) (2, 3) (2, 4)

三、解读

题目要求计算两个列表 A 和 B 的笛卡尔积,并以特定的格式打印结果。

from itertools import product
  • 从 Python 标准库中的 itertools 模块导入 product 函数。
  • product 函数用于计算输入的可迭代对象的笛卡尔积。
print("Please enter the element of list A, separated by spaces:")
A = list(map(int, input().split()))
print("Please enter the element of list B, separated by spaces:")
B = list(map(int, input().split()))
  • 用 input() 函数读取用户输入的字符串。
  • 用 split() 方法将输入的字符串按空格分割成多个子字符串。
  • 用 map() 函数将分割后的字符串列表转换为整数列表。int 是 map() 函数的参数,表示将每个字符串转换为整数。
  • 将 map 对象转换为列表,并将其存储在变量 A / B 中。
cartesian_product = list(product(A, B))
output = ' '.join([f'({a}, {b})' for a, b in cartesian_product])
print(output)
  • 用 product(A, B) 计算列表 A 和 B 的笛卡尔积。将生成所有可能的有序对 (a, b) ,其中 a 来自列表A ,b来自列表B。
  • 将 product 函数返回的迭代器转换为列表,并存储在变量 cartesian_product 中。
  • 用列表推导式和字符串格式来创建一个包含格式化后的笛卡尔积元组的字符串列表。
  • 列表推导式遍历 cartesian_product 中的每个元组(a, b),使用 f'({a}, {b})' 格式化每个元组为字符串形式。
  • 使用 ' '.join() 方法将这些字符串连接成一个单一的字符串,元素之间用空格分隔。
print(*cartesian_product)
  • 使用星号操作符 * 将 cartesian_product 列表解包,并将每个元组作为独立的参数传递给 print 函数。
  • 这将打印出 cartesian_product 中的每个元组。

 

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com