【问题标题】:int() not working for floats?int() 不适用于浮点数?
【发布时间】:2016-09-23 01:50:00
【问题描述】:

我最近在 Python 3.5 中遇到了这个问题:

>>> flt = '3.14'
>>> integer = '5'
>>> float(integer)
5.0
>>> float(flt)
3.14
>>> int(integer)
5
>>> int(flt)
Traceback (most recent call last):
  File "<pyshell#7>", line 1, in <module>
    int(flt)
ValueError: invalid literal for int() with base 10: '3.14'

这是为什么?它似乎应该返回3。我做错了什么,还是有充分的理由发生这种情况?

【问题讨论】:

  • 重点:如果不赋值float(flt)的结果,例如flt = float(flt),则转换后的值被丢弃。它不会就地更改它的参数(Python 没有与 C++ 传递引用等效的概念来允许这样做),因此int(flt) 是在原始str 上运行的,而不是float。基本上,int()floats 配合得很好,但你没有给它float

标签: python python-3.x floating-point int


【解决方案1】:

int() 需要一个包含整数文字的数字或字符串。根据Python 3.5.2 文档:

如果 x 不是数字或者如果 base 给出,那么 x 必须是字符串,bytes,或bytearray 实例表示基数 中的整数文字。 (强调)

意思是int()只能转换包含整数的字符串。您可以轻松做到这一点:

>>> flt = '3.14'
>>> int(float(flt))
3

这会将flt 转换为浮点数,然后对int() 有效,因为它是一个数字。然后它将通过删除小数部分转换为整数。

【讨论】:

  • 感谢您的回答,但这是为什么呢?似乎它应该工作。我知道 Python 不允许你这样做,但看起来很奇怪。
  • @nedla2004 有一个 intfloat 函数是有原因的。 int 用于整数转换,float 用于浮点转换。 float 没有就地转换。
  • 谢谢,现在更有意义了。
【解决方案2】:

它不起作用,因为flt 不是整数的字符串表示形式。您需要先将其转换为float,然后再转换为int

例如

flt = '3.14'
f = int(float(flt))

输出是

3

【讨论】:

    【解决方案3】:

    其他答案已经为您的问题提供了很好的解释,另一种理解正在发生的事情的方法是:

    import sys
    
    for c in ['3.14', '5']:
        try:
            sys.stdout.write(
                "Casting {0} {1} to float({0})...".format(c, c.__class__))
            value = float(c)
            sys.stdout.write("OK -> {0}\n".format(value))
            print('-' * 80)
        except:
            sys.stdout.write("FAIL\n")
    
        try:
            sys.stdout.write(
                "Casting {0} {1} to int({0})...".format(c, c.__class__))
            value = int(c)
            sys.stdout.write("OK -> {0}\n".format(value))
        except:
            sys.stdout.write("FAIL\n")
            sys.stdout.write("Casting again using int(float({0}))...".format(value))
            value = int(float(c))
            sys.stdout.write("OK -> {0}\n".format(value))
            print('-' * 80)
    

    哪些输出:

    Casting 3.14 <class 'str'> to float(3.14)...OK -> 3.14
    --------------------------------------------------------------------------------
    Casting 3.14 <class 'str'> to int(3.14)...FAIL
    Casting again using int(float(3.14))...OK -> 3
    --------------------------------------------------------------------------------
    Casting 5 <class 'str'> to float(5)...OK -> 5.0
    --------------------------------------------------------------------------------
    Casting 5 <class 'str'> to int(5)...OK -> 5
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-22
      • 2018-03-23
      • 2012-04-19
      • 1970-01-01
      • 2020-02-07
      相关资源
      最近更新 更多