Python convert Tuple to Integer

前端 未结 8 673
心在旅途
心在旅途 2021-01-02 03:10

Is there any function that can convert a tuple into an integer?

Example:

input = (1, 3, 7)

output = 137
8条回答
  •  遥遥无期
    2021-01-02 03:35

    How about:

    In [19]: filter(set('0123456789').__contains__,str((1,2,3)))
    Out[19]: '123'
    

    I believe this is the simplest solution.

    A very fast solution is:

    plus=ord("0").__add__ # separate out for readability; bound functions are partially-applied functions
    int(str(bytearray(map(plus,x)))) #str is necessary
    

    How that stacks up against the next-fastest solution:

    $ python -m timeit -s 'x=tuple(list(range(1,10))*10)' 'plus=ord("0").__add__;int(str(bytearray(map(plus,x))))'
    10000 loops, best of 3: 47.7 usec per loop
    
    $ python -m timeit -s "x=tuple(list(range(1,10))*10)" "int(''.join(map(str, x)))"
    10000 loops, best of 3: 59 usec per loop
    

提交回复
热议问题