user14278898
user14278898

Reputation: 53

Convert output printed on different lines into list python

I've been puzzling through this and can't seem to figure it out.

I have a large data set and have calculated some float objects, which prints each output in a new line when I print it (example subset of data below):

print(x)
> 1.22
> 1.33
> 1.44

I would like to convert these values to a list of strings:

['1.22','1.33','1.44']

I have tried converting the float objects to a string and following a similar suggestion here and then trying to combine the lists using itertools.

x_in_list = [y for y in (i.strip() for i in str(x).splitlines()) if y]
x_combined = itertools.chain(*x_in_list)

Which gives me a lot of:

<itertools.chain object at 0x7ff6d00c2160>
<itertools.chain object at 0x7ff6e012f040>
<itertools.chain object at 0x7ff6d00c2250>

I think the problem has something to do with the fact I'm working with float objects here. I understand that I could probably do this in a simpler, more elegant way within my original loop, but now that I've started I'd really like to figure this out.

Upvotes: 1

Views: 704

Answers (1)

Melvin Abraham
Melvin Abraham

Reputation: 3036

Seems like x is a string with \n as delimiter. You can just use split() method of string to split x based on that delimiter.

You could simply do:

x_in_list = x.split()

By default split() splits the string based on whitespaces and newline characters.

Upvotes: 4

Related Questions