What’s the most efficient way to compare two python values both of which are probably strings, but might be integers. So far I’m using str(x)==str(y) but that feels inefficient and (more importantly) ugly:
>>> a = 1.0
>>> b = 1
>>> c = '1'
>>> a == b
True
>>> b == c
False # here I wanted this to be true
>>> str(b)==str(c)
True # true, as desired
My actual objects are dictionary values retrieved with get(), and most of them are strings.
Test it out. I like using
%timeitinipython:In [1]: %timeit str("1") == str(1) 1000000 loops, best of 3: 702 ns per loop In [2]: %timeit "1" == str(1) 1000000 loops, best of 3: 412 ns per loop In [3]: %timeit int("1") == 1 1000000 loops, best of 3: 906 ns per loopApart from that, though, if you truly don’t know what the input type is, there isn’t much you can do about it, unless you want to make assumptions about the input data. For example, if you assume that most of the inputs are equal (same type, same value), you could do something like:
Which would be faster if they are normally the same type and normally equal… But it will be slower if they aren’t normally the same type, or aren’t normally equal.
However, are you sure you can’t cast everything to a str/int when they enter your code?