Python中怎么遍历列表的笛卡尔积

avatar
作者
猴君
阅读量:1

在Python中,可以使用itertools.product()函数来遍历列表的笛卡尔积。下面是一个简单的示例:

import itertools  list1 = [1, 2, 3] list2 = ['a', 'b', 'c']  cartesian_product = list(itertools.product(list1, list2))  for pair in cartesian_product:     print(pair) 

在上面的示例中,首先导入itertools模块,然后定义了两个列表list1list2。接着使用itertools.product()函数来计算这两个列表的笛卡尔积,并将结果存储在cartesian_product中。最后通过循环遍历cartesian_product,并打印每个元素对。

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!