I am trying to iterate over list of strings to add both floats and ints to another list. My code below works for ints, but not for floats and I don't know why.
My pseudo code would be: for element in list, if element is float or int, add to list.
So in the code below I use these two inputs, but you will see the issues. How can I fix this?
theInput1 = "3.2+.4*5.67/6.145="
theInput2 = "11.897/3.4+9.2-0.4*6.9/12.6-16.7="
And here is my code below when I use the first input:
import re
a = "3.2+.4*5.67/6.145="
a2 = [x for x in re.split("(\d*\.?\d*)", a) if x != '']
s = []
for i in a2:
if i >='0' and i <='9':
s.append(i)
print(s)
This is the output that I get:
['3.2', '5.67', '6.145']
I'm not sure what happened to the 0.4?
The result for the second input:
['11.897', '3.4', '0.4', '6.9', '12.6', '16.7']
Again the 9.2 is missing...
For this input without floats it works fine:
"(12+3)*(56/2)/(34-4)="
I get this output which works:
['12', '3', '56', '2', '34', '4']
Another option is to use re.findall instead of split:
import re
def get_numbers(s):
floats = []
ints = []
for x in re.findall(r"\d*\.?\d+", s):
if '.' in x:
floats.append(float(x))
else:
ints.append(int(x))
return floats, ints
# For Display
print('Floats', get_numbers("11.897/3.4+9.2-0.4*6.9/12.6-16.7=")) # Floats Only
print('Ints ', get_numbers("(12+3)*(56/2)/(34-4)=")) # Ints Only
print('Mixed ', get_numbers("(12+.3)*(56.36/2.15)/(34-4)=")) # Mixed
Output:
Floats ([11.897, 3.4, 9.2, 0.4, 6.9, 12.6, 16.7], [])
Ints ([], [12, 3, 56, 2, 34, 4])
Mixed ([0.3, 56.36, 2.15], [12, 34, 4])
The individual lists can be accessed like so:
f, i = get_numbers("(12+.3)*(56.36/2.15)/(34-4)=")
The problem is in comparison i <= "9"
. Obviously "9.2"
fails the check so it isn't added to the list.
You can try:
import re
a = "11.897/3.4+9.2-0.4*6.9/12.6-16.7="
a2 = [x for x in re.split(r"(\d*\.?\d*)", a) if x != ""]
s = []
for i in a2:
try:
s.append(float(i))
except ValueError:
continue
print(s)
Prints:
[11.897, 3.4, 9.2, 0.4, 6.9, 12.6, 16.7]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.