Python convert Tuple to Integer

前端 未结 8 581
心在旅途
心在旅途 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:45

    @Marcin bytearray solution is indeed the fastest one in Python 2.

    Following the same line in Python 3 one could do:

    >>> plus = ord("0").__add__
    >>> int(bytes(map(plus, x)))
    

    Python 3 handles string and bytes in a different way than Python 2, so in order to understand better the situation I did a little timings. The following are the results I got on my machine.

    With Python 2.7 (code):

    int(str(bytearray(map(plus, x))))           8.40 usec/pass
    int(bytearray(map(plus, x)).decode())       9.85 usec/pass
    int(''.join(map(str, x)))                   11.97 usec/pass
    reduce(lambda rst, d: rst * 10 + d, x)      22.34 usec/pass
    

    While with Python 3.2 (code):

    int(bytes(map(plus, x)))                    7.10 usec/pass
    int(bytes(map(plus, x)).decode())           7.80 usec/pass
    int(bytearray(map(plus,x)).decode())        7.99 usec/pass
    int(''.join(map(str, x)))                   17.46 usec/pass
    reduce(lambda rst, d: rst * 10 + d, x)      19.03 usec/pass
    

    Judge by yourselves :)

    0 讨论(0)
  • 2021-01-02 03:46
    >>> reduce(lambda rst, d: rst * 10 + d, (1, 2, 3))
    123
    
    0 讨论(0)
提交回复
热议问题