python float to in int conversion

前端 未结 4 1908
孤城傲影
孤城傲影 2021-01-12 08:26

I have an issue that really drives me mad. Normally doing int(20.0) would result in 20. So far so good. But:

levels = [int(gex_dict         


        
相关标签:
4条回答
  • 2021-01-12 08:57

    It looks like the problem is that gex_dict[i] actually returns a string representation of a float '20.0'. Although int() has the capability to cast from a float to an int, and a string representation of an integer to an int. It does not have the capability to cast from a string representation of a float to an int.

    The documentation for int can be found here: http://docs.python.org/library/functions.html#int

    0 讨论(0)
  • 2021-01-12 08:57

    The problem is that you have a string and not a float, see this as comparison:

    >>> int(20.0)
    20
    >>> int('20.0')
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    ValueError: invalid literal for int() with base 10: '20.0'
    

    You can workaround this problem by first converting to float and then to int:

    >>> int(float('20.0'))
    20
    

    So it would be in your case:

    levels = [int(float(gex_dict[i])) for i in sorted(gex_dict.keys())]
    
    0 讨论(0)
  • 2021-01-12 09:08

    '20.0' is a string, not a float; you can tell by the single-quotes in the error message. You can get an int out of it by first parsing it with float, then truncating it with int:

    >>> int(float('20.0'))
    20
    

    (Though maybe you'd want to store floats instead of strings in your dictionary, since that is what you seem to be expecting.)

    0 讨论(0)
  • 2021-01-12 09:13

    It looks like the value is a string, not a float. So you need int(float(gex_dict[i]))

    0 讨论(0)
提交回复
热议问题