【发布时间】:2018-04-10 15:47:46
【问题描述】:
我正在尝试将列表写入 csv 文件。 我面临几个问题。
- writer = csv.writer(f) AttributeError: 'list' object has no attribute 'writer'
我用这个link 来解决它并且它有效,并且只打印了第二个而不写第一个和第三个。
这是@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 的列表。这个问题已经解决了。当我使用上面的链接解决第一个问题时,代码运行但没有写入 csv 文件。 我尝试将第一个问题的解决方案与@gumboy 代码结合起来,代码如下:
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 (products)
f = open("H.csv", 'w')
hasil = ("costummer", x, "buy", products)
hasilstr = (','.join([str(x) for x in hasil]))
print (hasilstr)
f.write(hasilstr)
就像我上面提到的,代码可以工作,但只打印第二个,而不打印第一个和第三个元素。
打印功能与写入 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]
【问题讨论】: