0
我正在使用python 2.7 iter.product生成三个数据集的笛卡尔乘积。将标签添加到由itertools.product生成的数据集
这与三个嵌套循环相同。然而,在进入循环之前,我想打印标签“水果类型:”和“树类型:”如果不清楚,我把下面的输出示例。
什么是pythonic方式做到这一点,我可以产生笛卡儿。产品的集合,然后添加标签后处理,但不会失去使用itertools减少内存占用的目的?
代码示例
import itertools
FRUITS=['apple','orange','pear']
TREES=['ash','oak','beech']
ANIMALS=['dog','cat','horse']
def foo(a,b,c):
print "fruit is " + str(a) + ", tree is " + str(b) + ", animal is " + str(c)
[ foo(a,b,c) for a, b, c in itertools.product(FRUITS, TREES, ANIMALS)]
输出想要
*************************************** Fruit Type: apple *************************************** --------------------------------------- Tree Type: ash --------------------------------------- fruit is apple, tree is ash, animal is dog fruit is apple, tree is ash, animal is cat fruit is apple, tree is ash, animal is horse --------------------------------------- Tree Type: oak --------------------------------------- fruit is apple, tree is oak, animal is dog fruit is apple, tree is oak, animal is cat fruit is apple, tree is oak, animal is horse --------------------------------------- Tree Type: beech --------------------------------------- fruit is apple, tree is beech, animal is dog fruit is apple, tree is beech, animal is cat fruit is apple, tree is beech, animal is horse --------------------------------------- Tree Type: ash --------------------------------------- *************************************** Fruit Type: orange *************************************** --------------------------------------- Tree Type: ash --------------------------------------- fruit is orange, tree is ash, animal is dog fruit is orange, tree is ash, animal is cat fruit is orange, tree is ash, animal is horse --------------------------------------- Tree Type: oak --------------------------------------- fruit is orange, tree is oak, animal is dog fruit is orange, tree is oak, animal is cat fruit is orange, tree is oak, animal is horse --------------------------------------- Tree Type: beech --------------------------------------- fruit is orange, tree is beech, animal is dog fruit is orange, tree is beech, animal is cat fruit is orange, tree is beech, animal is horse *************************************** Fruit Type: pear *************************************** --------------------------------------- Tree Type: ash --------------------------------------- fruit is pear, tree is ash, animal is dog fruit is pear, tree is ash, animal is cat fruit is pear, tree is ash, animal is horse --------------------------------------- Tree Type: oak --------------------------------------- fruit is pear, tree is oak, animal is dog fruit is pear, tree is oak, animal is cat fruit is pear, tree is oak, animal is horse --------------------------------------- Tree Type: beech --------------------------------------- fruit is pear, tree is beech, animal is dog fruit is pear, tree is beech, animal is cat fruit is pear, tree is beech, animal is horse