-1

I have created a script with unique combinations, but I'm stuck on how to go about writing it into a csv file. Right now it's just printing out in my command line and hard to get a good grasp of the data.

My code:

from itertools import combinations, product

crust = ['Thin Crust', 'Hand Tossed']
topping = ['Bacon', 'Pepperoni', 'Steak']
sauce = ['Tomato', 'BBQ', 'Ranch']

topping_combs = combinations(topping, r=2)
sauce_combs = combinations(sauce, r=2)

topping_combs = list(topping_combs)
sauce_combs = list(sauce_combs)

prod = product(crust, topping_combs, sauce_combs)
for c, t, s in prod:
    print(c, *t, *s, sep=', ')
mcfadX
  • 83
  • 1
  • 4
  • 1
    Use a debugger. Inspect what `c`, `t`, and `s` look like. Then construct a list that looks like a row of the CSV you want and use `csv.writer` There is nothing special about creating CSV files from the result of an `itertools.product` call. The SO question covering CSV files is here: https://stackoverflow.com/questions/2084069/create-a-csv-file-with-values-from-a-python-list – Pranav Hosangadi May 12 '21 at 18:45

1 Answers1

1

Here is the code. It will open the csv file and write it with each iteration of the for loop. You will see one item in each cell as it was given in the terminal.

from itertools import combinations, product
import csv
crust = ['Thin Crust', 'Hand Tossed']
topping = ['Bacon', 'Pepperoni', 'Steak']
sauce = ['Tomato', 'BBQ', 'Ranch']

topping_combs = combinations(topping, r=2)
sauce_combs = combinations(sauce, r=2)

topping_combs = list(topping_combs)
sauce_combs = list(sauce_combs)

prod = product(crust, topping_combs, sauce_combs)
combine_list=[]
with open('Book1.csv', 'w', newline='') as file:
    for c, t, s in prod:
        print(c, *t, *s, sep=', ')

        writer = csv.writer(file)
        writer.writerow([c,*t,*s])