使用 itertools.product 写入 csv 文件

问题描述

我创建了一个具有独特组合的脚本,但我一直在思考如何将其写入 csv 文件。现在它只是在我的命令行中打印出来,很难很好地掌握数据。

我的代码

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=',')

解决方法

这是代码。它将打开 csv 文件并在 for 循环的每次迭代中写入它。您将在每个单元格中看到一个项目,因为它是在终端中给出的。

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,*s])

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...