I have a float:
pi = 3.141
And want to separate the digits of the float and put them into a list as intergers like this:
#[3, 1, 4, 1]
I know to to separate them and put them into a list but as strings and that doesnt help me
You need to loop through the string representation of the number and check if the number is a digit. If yes, then add it to the list. This can be done by using a list comprehension.
>>> pi = 3.141
>>> [int(i) for i in str(pi) if i.isdigit()]
[3, 1, 4, 1]
Another way using Regex (Not - preffered)
>>> map(int,re.findall('\d',str(pi)))
[3, 1, 4, 1]
A final way - Brute force
>>> pi = 3.141
>>> x = list(str(pi))
>>> x.remove('.')
>>> map(int,x)
[3, 1, 4, 1]
Few references from the docs
str.isdigitre.findallmapThe timeit results
python -m timeit "pi = 3.141;[int(i) for i in str(pi) if i.isdigit()]"
100000 loops, best of 3: 2.56 usec per loop
python -m timeit "s = 3.141; list(map(int, str(s).replace('.','')))" # Avinash's Method
100000 loops, best of 3: 2.54 usec per loop
python -m timeit "import re;pi = 3.141; map(int,re.findall('\d',str(pi)))"
100000 loops, best of 3: 5.72 usec per loop
python -m timeit "pi = 3.141; x = list(str(pi));x.remove('.'); map(int,x);"
100000 loops, best of 3: 2.48 usec per loop
As you can see the brute force method is the fastest. The Regex answer as known is the slowest.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With