在Python中获取整数的一部分

5
有没有一种优雅的方式(也许可以使用 numpy)来获取 Python 整数的指定部分,例如说我想从 1990 中获取 90
我可以这样做:
my_integer = 1990
int(str(my_integer)[2:4])
# 90

但这样做很丑陋。 还有其他选择吗?

你究竟想要实现什么? - fuenfundachtzig
我想获取一个整数的一部分,就像我在问题中所解释的那样。 - tagoma
4个回答

10

1990 % 100可以解决问题。

(%是模运算符,返回除法的余数,在这里1990=19*100+90。)


在答案被接受后添加:

如果你需要一些通用的东西,请尝试这个:

def GetIntegerSlice(i, n, m):
  # return nth to mth digit of i (as int)
  l = math.floor(math.log10(i)) + 1
  return i / int(pow(10, l - m)) % int(pow(10, m - n + 1))

它将返回i的第n到第m位数字(作为int类型),即:

>>> GetIntegerSlice(123456, 3, 4)
34

不确定它是否比您的建议更好,但它不依赖于字符串操作,写起来很有趣。

(注意:在进行除法运算之前将其转换为 int(而不仅在最后将结果强制转换为 int)也使其适用于长整数。)


这就是为什么我问他的原因。 - fuenfundachtzig
1
UpperCamelCase是Python函数的一种糟糕的命名约定,不要向初学者展示这些内容并停止编写它。请参阅此PEP8参考以了解“标准”是什么。即使您不想使用下划线小写,也不要使用大驼峰命名法。在Python中,这是一种耻辱。 - Bernardo Sulzbach

4

以下是获取任意数量尾数的通用函数:

In [160]: def get_last_digits(num, digits=2):
   .....:         return num%10**digits
   .....:

In [161]: get_last_digits(1999)
Out[161]: 99

In [162]: get_last_digits(1999,3)
Out[162]: 999

In [166]: get_last_digits(1999,10)
Out[166]: 1999

3
也许像这样:

可能是这样:

my_integer = 1990
my_integer % 100

3

取决于使用情况,但如果你知道你只需要最后两个数字,你可以使用模运算符,像这样:1990%100,得到的结果为90


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接