1

I append a few things and in the end i have a list that looks like this

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

Now i run this in a loop and at every iteration of the loop i get this list and i want to append this list to a csv with each line looking like this

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

i tried doing

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

but that gives a space for every number somewhat looking like this

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

Any ideas on how i may do this

Part of the code looks like this

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) 

Thanks in advance

asked Jul 31, 2018 at 17:57

2 Answers 2

3

Try:

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

Output:

53.02 12.36 120 33.6 0.32 65 52 26.3 66 39.12 0.65 96
answered Jul 31, 2018 at 18:02
Sign up to request clarification or add additional context in comments.

Comments

1

You're going a bit too deep - the .join() method works on any iterable object, including a String - which is what you're giving it. What you want is

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

See the inner square brackets, there, that bind [str(ele) for ele in listed] into a single iterable object, which will then be joined.

answered Jul 31, 2018 at 18:01

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.