2016-12-27 3 views
0

Я использую python 2.7 iter.product для генерации декартова произведения трех наборов данных.Добавление меток в набор данных, сгенерированный itertools.product

Это то же самое, что и три вложенных цикла. Однако перед входом в цикл я хочу напечатать ярлык «Тип фруктов:» и «Тип дерева:» Если это не ясно, я поставлю пример вывода, который я хочу ниже.

Что такое питонический способ сделать это, я мог бы создать декартов. продукт наборов, а затем добавить метки в пост-обработки, но разве это не означает, что цель использования 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 

ответ

1

это способ:

from itertools import product 

FRUITS = ['apple', 'orange', 'pear'] 
TREES = ['ash', 'oak', 'beech'] 
ANIMALS = ['dog', 'cat', 'horse'] 

lst = [(fruit, tree, animal) for fruit, tree in product(FRUITS, TREES) 
     for animal in ANIMALS] 

fmt = 'fruit is {} tree {} is animal is {}' 
last_tree_type = None 
last_fruit_type = None 
for item in lst: 
    if last_fruit_type != item[0]: 
     last_fruit_type = item[0] 
     print(20*'=') 
     print('fruit type: {}'.format(item[0])) 
     print(20*'=') 
    if last_tree_type != item[1]: 
     last_tree_type = item[1] 
     print(20*'-') 
     print('tree type: {}'.format(item[1])) 
     print(20*'-') 
    print(fmt.format(*item)) 

lst содержит триплетов [('apple', 'ash', 'dog'), ('apple', 'ash', 'cat'), ...]; остальное - это просто форматирование строки.

Обычно рекомендуется собирать ваши данные и выполнять строковое форматирование как можно позже.