Python|构造笛卡尔积元组列表
有时,在处理数据时,我们需要将数据创建为所有可能的容器对。这种类型的应用程序来自 Web 开发领域。让我们讨论可以执行此任务的某些方式。
方法#1:使用列表推导
这是执行此特定任务的单线方式。在此,我们只是将循环任务缩短为一行,以生成所有可能的带有列表元素的元组对。
# Python3 code to demonstrate working of
# Construct Cartesian Product Tuple list
# using list comprehension
# initialize list and tuple
test_list = [1, 4, 6, 7]
test_tup = (1, 3)
# printing original list and tuple
print("The original list : " + str(test_list))
print("The original tuple : " + str(test_tup))
# Construct Cartesian Product Tuple list
# using list comprehension
res = [(a, b) for a in test_tup for b in test_list]
# printing result
print("The Cartesian Product is : " + str(res))
输出 :
The original list : [1, 4, 6, 7]
The original tuple : (1, 3)
The Cartesian Product is : [(1, 1), (1, 4), (1, 6), (1, 7), (3, 1), (3, 4), (3, 6), (3, 7)]
方法#2:使用itertools.product()
此任务也可以使用单个函数执行,该函数在内部执行返回所需笛卡尔积的任务。
# Python3 code to demonstrate working of
# Construct Cartesian Product Tuple list
# using itertools.product()
from itertools import product
# initialize list and tuple
test_list = [1, 4, 6, 7]
test_tup = (1, 3)
# printing original list and tuple
print("The original list : " + str(test_list))
print("The original tuple : " + str(test_tup))
# Construct Cartesian Product Tuple list
# using itertools.product()
res = list(product(test_tup, test_list))
# printing result
print("The Cartesian Product is : " + str(res))
输出 :
The original list : [1, 4, 6, 7]
The original tuple : (1, 3)
The Cartesian Product is : [(1, 1), (1, 4), (1, 6), (1, 7), (3, 1), (3, 4), (3, 6), (3, 7)]