且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

仅第一个和第三个元素从python列表打印到csv文件

更新时间:2023-02-06 19:19:38

f = open('H.csv','w')所做的工作是将其写入文件,而且还覆盖数据.您需要做的是使用f =open('H.csv', 'a+'),每次都将新字符串追加到文件中.链接 要对数据进行排序

What you are doing with the f = open('H.csv','w') is that it is write to the file but also writing over your data. What you need to do is use f =open('H.csv', 'a+') this appends new string everytime to the file.link To sort data use

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

使用此代码,我可以将控制台上打印的内容写入文件.

With this code I was able to write to file what was printed on console.

csvfile = [['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 csvfile}
for x in sorted(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", 'a+')
    hasil = ("costummer", x, "buy", products)
    hasilstr = ("costummer, %s,buy,"+','.join([str(i) for i in products])) %(x)
    print (hasilstr)
    f.write(hasilstr +"\n")