获取Python中整数的第一个数字的最有效方法?

The most efficient way to get the first number of an integer in Python?

问题描述

我需要从给定的整数中获取第一个数字。此操作将执行数百万次,因此我需要确保使用最有效的方法。

如果整数的长度影响答案,那么在我的例子中,我知道整数将始终是 2 位数字。

我试过的

下面的方法我都试过了。方法 1 和 2 似乎很慢,因为我必须来回转换。方法 3 使用 //、** 和 %,我认为它们对系统的影响也很大。有没有更好的方法来完成这个看似“简单”的任务?

# Method 1:
first_digit = int(str(x)[0])

# Method 2:
first_digit = int(str(x)[1:])

# Method 3:
first_digit = x // 10 % 10

如果数字不超过 2 位,则 % 10 无效。但它也可以只有一个数字吗?在那种情况下,结果将为零,这是错误的。所以,假设数字不超过 2 位,公式可以是:

if x > 9: 
    return x // 10;
return x

我使用 timeit 模块为您的方法计时, 重复 1000 万次:

from timeit import timeit

n = 10000000
print(timeit(stmt='import random; n = random.randint(10, 99); x = int(str(n)[0])', number=n))
print(timeit(stmt='import random; n = random.randint(10, 99); x = int(str(n)[1:])', number=n))
print(timeit(stmt='import random; n = random.randint(10, 99); x = n // 10 % 10', number=n))
print(timeit(stmt='import random; n = random.randint(10, 99); x = n//10 if n>9 else n', number=n))

这给了我以下结果:

10.7325472
11.0877854
8.493264900000003
8.550117300000004

似乎x // 10 % 10方法比其他方法快一点。