Nope Nope - 11 months ago 38
Python Question

Python: Convert list of ints to one number?

I have a list of integers that I would like to convert to one number like:

numList = [1,2,3]
num = magic(numList)

print num, type(num)
>>> 123, <type 'int'>

What is the best way to implement the magic function?

Thanks for your help.


I did find this, but it seems like there has to be a better way.


Let's give some credit to Triptych and cdleary for their great answers! Thanks guys.

# Over-explaining a bit:
def magic(numList):         # [1,2,3]
    s = map(str, numList)   # ['1','2','3']
    s = ''.join(s)          # '123'
    s = int(s)              # 123
    return s

# How I'd probably write it:
def magic(numList):
    s = ''.join(map(str, numList))
    return int(s)

# As a one-liner  
num = int(''.join(map(str,numList)))

# Functionally:
s = reduce(lambda x,y: x+str(y), numList, '')
num = int(s)

# Using some oft-forgotten built-ins:
s = filter(str.isdigit, repr(numList))
num = int(s)