views:

95

answers:

3

Hello,

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.

+1  A: 

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.

SilentGhost
+2  A: 

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
Vinay Sajip
`float('23')` doesn't raise ValueError and therefore will be appended.
SilentGhost
Of course, but it's application-dependent as to whether '23' is a valid float or not. The same would apply to exponential notation, e.g. `1e3`
Vinay Sajip
`'23'` is a string, your check is not correct.
SilentGhost
A: 

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.

Taurus Olson