Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/337.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
获取python中的最高有效数字_Python_List_Integer_Significant Digits - Fatal编程技术网

获取python中的最高有效数字

获取python中的最高有效数字,python,list,integer,significant-digits,Python,List,Integer,Significant Digits,假设我有列表[34523,55,65,2] 获取[3,5,6,2]最有效的方法是什么。如果可能,无需将每个数字更改为str()?假设您只处理正数,您可以将每个数字除以小于该数字的10的最大幂,然后计算结果 >>> from math import log10, floor >>> lst = [34523, 55, 65, 2] >>> [floor(x / (10**floor(log10(x)))) for x in lst] [3, 5

假设我有列表
[34523,55,65,2]


获取
[3,5,6,2]
最有效的方法是什么。如果可能,无需将每个数字更改为
str()

假设您只处理正数,您可以将每个数字除以小于该数字的10的最大幂,然后计算结果

>>> from math import log10, floor
>>> lst = [34523, 55, 65, 2]
>>> [floor(x / (10**floor(log10(x)))) for x in lst]
[3, 5, 6, 2]
如果您使用的是Python3,那么您可以使用整数除法运算符
/
,而不是将结果放在地板上:

>>> [x // (10**floor(log10(x))) for x in lst]
[3, 5, 6, 2]
但是,我不知道这是否比转换为字符串并切分第一个字符更有效。(请注意,如果必须处理0到1之间的数字,则需要更加复杂。)


如果这是在一段性能关键的代码中,您应该测量这两个选项,看看哪个更快。如果它不在性能关键的代码中,请使用您最容易阅读的代码。

我使用python 3.6.1进行了一些计时:

from timeit import timeit

from math import *


lst = list(range(1, 10_000_000))


# 3.6043569352230804 seconds
def most_significant_str(i):
    return int(str(i)[0])


# 3.7258850016013865 seconds
def most_significant_while_floordiv(i):
    while i >= 10:
        i //= 10
    return i


# 4.515933519736952 seconds
def most_significant_times_floordiv(i):
    n = 10
    while i > n:
        n *= 10
    return i // (n//10)


# 4.661690454738387 seconds
def most_significant_log10_floordiv(i):
    return i // (10 ** (log10(i) // 1))


# 4.961193803243334 seconds
def most_significant_int_log(i):
    return i // (10 ** int(log10(i)))


# 5.722346990002692 seconds
def most_significant_floor_log10(i):
    return i // (10 ** floor(log10(i)))


for f in (
    'most_significant_str',
    'most_significant_while_floordiv',
    'most_significant_times_floordiv',
    'most_significant_log10_floordiv',
    'most_significant_int_log',
    'most_significant_floor_log10',
):
    print(
        f,
        timeit(
            f"""
for i in lst:
    {f}(i)
            """,
            globals=globals(),
            number=1,
        ),
    )
如您所见,对于
范围(1,10_000_000)
中的数字,
int(str(i)[0])
比其他方法更快。我能得到的最接近的方法是使用一个简单的while循环:

def most_significant_while_floordiv(i):
    while i >= 10:
        i //= 10
    return i

该死,你把我打败了,也考虑了十分的循环,如果日志和地板是昂贵的,如果你只有积分器,看一看。这是你问题的C版本。
def most_significant_while_floordiv(i):
    while i >= 10:
        i //= 10
    return i