如何检查值是否逻辑整数? [英] How to check if value is logically integer?

查看:87
本文介绍了如何检查值是否逻辑整数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些函数在做数学的东西需要取整数agrmuents。

I have some functions doing math stuff which needs to take integer agrmuents.

我知道我可以强制使用 int 使用条件 isinstance(x,int)

或更严格 type(x)== int ,但是IMO它不是pythonic。

我认为我的Python代码不应该拒绝 2.0 因为它是 float

I know that I can force using int by using condition isinstance(x, int)
or more strict type(x) == int, but IMO it isn't pythonic.
I think my Python code shouldn't reject 2.0 just because it's float.

检查值是否逻辑整数的最佳方法是什么?

What's the best way to check if value is logically integer?

逻辑整数我的意思是任何类型的值,它代表整数。

By logically integer I mean value of any type, which represents integer.

能够用于算术操作,如 int ,但我没有检查它,

,因为我相信在Python 任何条件都会被愚弄。

It should be able to be used in arithmetic operations like int, but I don't have to check it,
because I belive that in Python any set of conditions can get fooled.

例如,

True -2 2.0 十进制(2)分数(4,2 ) 逻辑整数

'2'时2.5 不是。

For example,
True, -2, 2.0, Decimal(2), Fraction(4, 2) are logically integers,
when '2' and 2.5 are not.

目前我使用 int(x)== x ,但我不确定它是否是最佳解决方案。

我知道我可以使用 float(x).is_integer()
我还看到 x%1 == 0

At the moment I use int(x) == x, but I'm not sure if it's the best solution.
I know I can use float(x).is_integer(). I also saw x % 1 == 0.

推荐答案

通常会检查 Integral ABC(抽象基类),但浮点值通常不会被视为整数,无论​​它们的值如何。如果您需要,请记下他们的 is_integer 属性:

Normally one would check against the Integral ABC (Abstract Base Class), but floating point values are not normally meant to be treated as integers no matter their value. If you want that, take note of their is_integer property:

(1324.34).is_integer()
#>>> False

(1324.00).is_integer()
#>>> True

然后代码就是:

from numbers import Integral

def is_sort_of_integer(value):
    if isinstance(value, Integral):
        return True

    try:
        return value.is_integer()

    except AttributeError:
        return False

如果您还想处理十进制 s,分数等等,没有 is_integer 方法,最好的选择可能就是:

If you also want to deal with Decimals, Fractions and so on, which don't have an is_integer method, the best option would probably be just:

from numbers import Number, Integral

def is_sort_of_integer(value):
    if isinstance(value, Integral):
        return True

    if isinstance(value, Number):
        try:
            return not value % 1
        except TypeError:
            return False

    return False

积分检查在这种情况下不应该,但最好保留它。

The Integral check shouldn't be needed in this case, but it's probably best to keep it.

这篇关于如何检查值是否逻辑整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆