1

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.

1
  • 1
    itertools.chain(*x_in_list) must be list(itertools.chain.from_iterable(x_in_list) . Commented Nov 17, 2020 at 5:32

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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.