开发者

Converting a list of integers into a single value

If I had list of integers say,

x = [1,2,3,4,5]

Is there an in-built function that can convert this into a single number like 12345? If not, what's the开发者_运维问答 easiest way?


>>> listvar = [1,2,3,4,5]
>>> reduce(lambda x,y:x*10+y, listvar, 0)
12345


If they're digits like this,

sum(digit * 10 ** place for place, digit in enumerate(reversed(x)))


int("".join(str(X) for X in x))

You have not told us what the result for x = [1, 23, 4] should be by the way... My answer gives 1234, others give 334


Just for fun :)

int(str(x)[1:-1].replace(', ', ''))

Surprisingly, this is even faster for large list:

$ python -m timeit -s "x=[1,2,3,4,5,6,7,8,9,0]*100" "int(str(x)[1:-1].replace(', ', ''))"
10000 loops, best of 3: 128 usec per loop

$ python -m timeit -s "x=[1,2,3,4,5,6,7,8,9,0]*100" "int(''.join(map(str, x)))"
10000 loops, best of 3: 183 usec per loop

$ python -m timeit -s "x=[1,2,3,4,5,6,7,8,9,0]*100" "reduce(lambda x,y:x*10+y, x, 0)"
1000 loops, best of 3: 649 usec per loop

$ python -m timeit -s "x=[1,2,3,4,5,6,7,8,9,0]*100" "sum(digit * 10 ** place for place, digit in enumerate(reversed(x)))"
100 loops, best of 3: 7.19 msec per loop

But for very small list (maybe more common?) , this one is slowest.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜