只有第一个和第三个元素从python列表打印到csv-fi

2024-09-30 01:23:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试将列表写入csv文件。 我面临几个问题。在

  1. 写入程序=作家.csv(f) AttributeError:“list”对象没有属性“writer”

我用这个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]

Tags: 文件csvthe代码in列表forbuy
2条回答

问题是在for循环的每次迭代中都会再次打开文件(只打开一次),然后重写它,因为您将'w'作为“mode”参数传递(如果您只想在文件中附加一些内容,可以传递“a”)。在

您实际应该做的是,导入csv模块,用with语句打开文件,创建一个writer writer = csv.writer(csv_file),在for循环中写入头和行。(另外,重命名csv列表,因为csv是模块的名称。)

import csv


lst = [...]  # Your csv list.
csvdict = {words[0]:words[1:] for words in lst}

with open('temp.csv', 'w', newline='') as csv_file:
    writer = csv.writer(csv_file, delimiter=';')
    writer.writerow(('costumer', 'buy'))  # Write the header.
    for costumer in csvdict:
        products = [index for index, v in enumerate(csvdict[costumer], 1) if v == '1']
        writer.writerow((costumer, products))

生成的csv文件如下所示(第一列包含客户,第二列包含产品):

^{pr2}$

使用f = open('H.csv','w')所做的是,它写入文件,同时也写入数据。您需要做的是使用f =open('H.csv', 'a+')这会在每次文件中附加新的字符串。link 排序数据使用

for x in sorted(csvdict.keys()):

有了这段代码,我可以将控制台上打印的内容写入文件。在

^{pr2}$

相关问题 更多 >

    热门问题