簡體   English   中英

在 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模塊對您的方法以及dspr進行 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方法比其他方法快一點。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM