python float to in int conversion

前端 未结 4 1907
孤城傲影
孤城傲影 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 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.)

提交回复
热议问题