我正在尝试将列表写入csv文件。 我面临几个问题。在
我用这个link来解决它,它起作用了,只打印了第二个for而没有编写第一个和第三个for。在
这是@gumboy编写的代码
csv = [['1', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '1', '0', '0', '0', '0', '0', '0', '0', '0', '0', '1', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0'], ['2', '0', '0', '0', '0', '0', '0', '0', '1', '0', '0', '0', '1', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '1', '0', '0', '0', '0', '0', '0', '0', '1', '0', '0', '0', '0'], ['3', '0', '0', '0', '1', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '1', '0', '0', '0', '0', '0', '0', '0', '0', '1', '0', '0', '0', '0', '0', '0', '0']]
csvdict = {words[0]:words[1:] for words in csv}
for x in csvdict.keys(): # iterate over the keys '1', '2', ....
products = [index+1 for index,v in enumerate(csvdict[x]) if v == '1' ] # create list of purchases where the '1's are indexed
print ("costummer", x, "buy", products)
其思想是用列表索引替换包含1的list。这个问题已经解决了。当我使用上面的链接来解决第一个问题时,代码运行,但没有写入csv文件。 我试图将第一个问题的解决方案与@gumboy代码相结合,下面是代码:
^{pr2}$就像我上面提到的,代码正在工作,但是只打印第二个,而没有打印第一个和第三个元素。在
打印功能与在csv文件上写入的内容: 打印:
costummer,1,buy,[12, 22]
costummer,2,buy,[8, 12, 38, 46]
costummer,3,buy,[4, 34, 43]
csf文件:
costummer,2,buy,[8, 12, 38, 46]
问题是在for循环的每次迭代中都会再次打开文件(只打开一次),然后重写它,因为您将
'w'
作为“mode”参数传递(如果您只想在文件中附加一些内容,可以传递“a”)。在您实际应该做的是,导入
csv
模块,用with
语句打开文件,创建一个writerwriter = csv.writer(csv_file)
,在for循环中写入头和行。(另外,重命名csv
列表,因为csv
是模块的名称。)生成的csv文件如下所示(第一列包含客户,第二列包含产品):
^{pr2}$使用
f = open('H.csv','w')
所做的是,它写入文件,同时也写入数据。您需要做的是使用f =open('H.csv', 'a+')
这会在每次文件中附加新的字符串。link 排序数据使用有了这段代码,我可以将控制台上打印的内容写入文件。在
^{pr2}$相关问题 更多 >
编程相关推荐