问题描述
我创建了一个具有独特组合的脚本,但我一直在思考如何将其写入 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])