Extract only numbers from data in Jython
Question
Here is my problem. I'm working on a Jython program and I have to extract numbers from a PyJavaInstance:
[{string1="foo", xxx1, xxx2, ..., xxxN, string2="bar"}]
(where xxx are the floating point numbers).
My question is how can I extract the numbers and put them in a more simple structure like a python list.
Thank you in advance.
Solution
A PyJavaInstance
is a Jython wrapper around a Java instance; how you extract numbers from it depends on what it is. If you need to get a bunch of stuff - some of which are strings and some of which are floats, then:
float_list = []
for item in instance_properties:
try:
float_list.append(float(item))
except ValueError:
pass
OTHER TIPS
can you iterate and check whether an item is float? The method you're looking for is isinstance
. I hope it's implemented in Jython.
Thank you Vinay. It's also the kind of solution I've just found:
new_inst=[]
for element in instance:
try:
float(element)
new_inst.append(float(element))
except ValueError:
del(element)
@SilentGhost: Good suggestion. The issue was to find what method could determine if each element I iterate is a float number.