python float to in int conversion

前端 未结 4 1930
孤城傲影
孤城傲影 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    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 "", line 1, in 
    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())]
    

提交回复
热议问题