0

So I have this list:

a = '[47.2, 46.6, 46.4, 46.0, 45.7, 45.54, 45.29, 45.01, 44.79, 44.54, 44.15, 0.0]'

How can i pull all the floats and integers in order

I tried

import re
a = [float(s) for s in re.findall("\d+\.\d+", a)]

but doesn't pull integers

Expecting =

a = [47.2, 46.6, 46.4, 46, 45.7, 45.54, 45.29, 45.01, 44.79, 44.54, 44.15, 0]

2
  • 1
    can you elaborate more? do you want to sort the list which contains integer as well as floats? can you add sample output? Commented Oct 29, 2020 at 7:03
  • Does this answer your question? How to convert string representation of list to a list? Commented Oct 29, 2020 at 7:14

3 Answers 3

1

Keep it simple

spam = '[47.2, 46.6, 46.4, 46, 45.7, 45.54, 45.29, 45.01, 44.79, 44.54, 44.15, 0]'

#using json
import json
eggs = json.loads(spam)
print(eggs)

# ast.literal_eval
from ast import literal_eval
eggs = literal_eval(spam)
print(eggs)
Sign up to request clarification or add additional context in comments.

3 Comments

How come using json is easy and without knowing the background work? And clearly user has mentioned in the code using re in is code.
@SivaShanmugam, OP is asking to convert string representation of a list into list object. They are using re (because they don't know better, or for whatever reason). That doesn't mean we must stick to sub-optimal attempt to complete the task.
@SivaShanmugam, note that you can see examples of XYproblem. Some users may ask a question based on their attempt to complete some task (e.g. error they get), but actually what they want is not even in the question (i.e. actual task they try to complete). This one may well be one of them too.
1

Regex:

\d+(?:\.\d+)?

Code:

import re
a = [float(s) for s in re.findall("\d+(?:\.\d+)?", a)]
print (a)

Output:

[47.2, 46.6, 46.4, 46.0, 45.7, 45.54, 45.29, 45.01, 44.79, 44.54, 44.15, 0.0]

1 Comment

Glad to know. Please accept the answer, so that it easy for the people to not open the question again.
0

This is because you are including the . to be matched in the regex. Pls. change the regex for integers

You should use (\d+(?:\.\d+)?) instead of your regex

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.