将字符串写入csv

时间:2018-07-31 17:57:02

标签: python

我添加了一些内容,最后我得到了一个看起来像这样的列表

listed = ['53.02 12.36 120 33.6', 0.32 ,65 , '52 26.3 66 39.12' ,0.65 , 96]

现在我在一个循环中运行此循环,并且在循环的每次迭代中我都得到此列表,并且我希望将此列表附加到csv上,每行看起来像这样

53.02 12.36 120 33.6 0.32 65 52 26.3 66 39.12 0.65 96

我尝试做

        listed = ' '.join(str(ele) for ele in listed)

但是每个数字都有一个空格,看起来像这样

5,3,.,0,2, ,1,2,.,3,6, ,0,.,2

关于我该怎么做的任何想法

部分代码如下:

f = open('Testing.csv', 'a')
writer = csv.writer(f, delimiter = '\t')
for index in range(len(dataset_train)):

        for box, score, label in zip(image_boxes, image_scores, image_labels):
            box = str(box).lstrip('[').rstrip(']')
            listed.append(box)
            listed.append(score)
            listed.append(label)
        listed = ' '.join(str(ele) for ele in listed)
        listed = list(listed)
        writer.writerow(listed)                

预先感谢

2 个答案:

答案 0 :(得分:3)

尝试:

import csv
from itertools import chain

listed = ['53.02 12.36 120 33.6', 0.32 ,65 , '52 26.3 66 39.12' ,0.65 , 96]
listed = list(chain.from_iterable([str(i).split() for i in listed]))   #Flatten list

with open(filename, "w") as infile:
    writer = csv.writer(infile, delimiter = '\t')
    writer.writerow(listed)        #Write row

输出:

53.02   12.36   120 33.6    0.32    65  52  26.3    66  39.12   0.65    96

答案 1 :(得分:1)

您会做得太深了-.join()方法可在任何可迭代对象(包括字符串)上使用-这就是您所提供的。你想要的是

listed = ' '.join( [str(ele) for ele in listed] )

请参阅那里的内部方括号,将[str(ele) for ele in listed]绑定到单个可迭代对象中,然后将其合并。