How to convert a list of multiple integers into a single integer?

前端 未结 4 919
鱼传尺愫
鱼传尺愫 2021-01-11 09:02

How do I convert a list in Python 3.5 such as:

x=[1, 3, 5]

to an int of 135 (a whole int)?

4条回答
  •  春和景丽
    2021-01-11 10:04

    Using only math (no conversions to or from strings), you can use the reduce function (functools.reduce in Python 3)

    b = reduce(lambda total, d: 10*total + d, x, 0)
    

    This makes use of Horner's rule, which factors the polynomial representing the number to reduce the number of multiplications. For example,

    1357 = 1*10*10*10 + 3*10*10 + 5*10 + 7     # 6 multiplications
         = ((1*10 + 3)*10 + 5)*10 + 7          # 3 multiplications
    

    As a result, this is faster than computing powers of 10 or creating a string and converting the result to an integer.

    >>> timeit.timeit('reduce(lambda t,d: 10*t+d, x, 0)', 'from functools import reduce; x=[1,3,5,7]')
    0.7217515400843695
    >>> timeit.timeit('int("".join(map(str, [1,3,5,7])))')
    1.425914661027491
    >>> timeit.timeit('sum(d * 10**i for i, d in enumerate(x[::-1]))', 'x=[1,3,5,7]')
    1.897974518011324
    

    In fairness, string conversion is faster once the number of digits gets larger.

    >>> import timeit
    
    # 30 digits
    >>> setup='from functools import reduce; x=[5, 2, 6, 8, 4, 6, 6, 4, 8, 0, 3, 1, 7, 6, 8, 2, 9, 9, 9, 5, 4, 5, 5, 4, 3, 6, 9, 2, 2, 1]' 
    >>> print(timeit.timeit('reduce(lambda t,d: 10*t+d, x, 0)', setup))
    6.520374411018565
    >>> print(timeit.timeit('int("".join(map(str, x)))', setup))
    6.797425839002244
    >>> print(timeit.timeit('sum(d * 10**i for i, d in enumerate(x[::-1]))', setup))
    19.430233853985555
    
    # 60 digits
    >>> setup='from functools import reduce; x=2*[5, 2, 6, 8, 4, 6, 6, 4, 8, 0, 3, 1, 7, 6, 8, 2, 9, 9, 9, 5, 4, 5, 5, 4, 3, 6, 9, 2, 2, 1]' 
    >>> print(timeit.timeit('reduce(lambda t,d: 10*t+d, x, 0)', setup))
    13.648188541992567
    >>> print(timeit.timeit('int("".join(map(str, x)))', setup))
    12.864593736943789
    >>> print(timeit.timeit('sum(d * 10**i for i, d in enumerate(x[::-1]))', setup))
    44.141602706047706
    
    # 120 digits!
    >>> setup='from functools import reduce; x=4*[5, 2, 6, 8, 4, 6, 6, 4, 8, 0, 3, 1, 7, 6, 8, 2, 9, 9, 9, 5, 4, 5, 5, 4, 3, 6, 9, 2, 2, 1]' 
    >>> print(timeit.timeit('reduce(lambda t,d: 10*t+d, x, 0)', setup))
    28.364255172084086
    >>> print(timeit.timeit('int("".join(map(str, x)))', setup))
    25.184791765059344
    >>> print(timeit.timeit('sum(d * 10**i for i, d in enumerate(x[::-1]))', setup))
    99.88558598596137
    

提交回复
热议问题