【问题标题】:Writing to csv file with itertools.product使用 itertools.product 写入 csv 文件
【发布时间】:2021-05-12 17:31:48
【问题描述】:

我创建了一个具有独特组合的脚本,但我一直不知道如何将其写入 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=', ')

【问题讨论】:

  • 使用调试器。检查 cts 的外观。然后构建一个看起来像一行你想要的 CSV 的列表并使用csv.writeritertools.product 调用的结果创建 CSV 文件并没有什么特别之处。涵盖 CSV 文件的 SO 问题在这里:stackoverflow.com/questions/2084069/…

标签: python-3.x csv export-to-csv itertools


【解决方案1】:

这里是代码。它将打开 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,*t,*s])

【讨论】:

  • 为什么是combine_list=[]
  • 其实我忘了删除那段代码
猜你喜欢
  • 2011-08-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多