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]

  • 1
    can you elaborate more? do you want to sort the list which contains integer as well as floats? can you add sample output? – x899 Oct 29 '20 at 07:03
  • Does this answer your question? [How to convert string representation of list to a list?](https://stackoverflow.com/questions/1894269/how-to-convert-string-representation-of-list-to-a-list) – buran Oct 29 '20 at 07:14

3 Answers3

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]
Siva Shanmugam
  • 627
  • 7
  • 17
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)
buran
  • 7,974
  • 4
  • 20
  • 41
  • 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. – Siva Shanmugam Oct 29 '20 at 07:17
  • @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. – buran Oct 29 '20 at 07:20
  • Good. Thanks for the explanation. – Siva Shanmugam Oct 29 '20 at 07:24
  • @SivaShanmugam, note that you can see examples of [XYproblem](https://en.wikipedia.org/wiki/XY_problem). 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. – buran Oct 29 '20 at 07:30
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

Simplecode
  • 434
  • 2
  • 11