I have a list of integers that I would like to convert to one number like:
JavaScript
x
6
1
numList = [1, 2, 3]
2
num = magic(numList)
3
4
print num, type(num)
5
>>> 123, <type 'int'>
6
What is the best way to implement the magic function?
EDIT
I did find this, but it seems like there has to be a better way.
Advertisement
Answer
JavaScript
1
27
27
1
# Over-explaining a bit:
2
def magic(numList): # [1,2,3]
3
s = map(str, numList) # ['1','2','3']
4
s = ''.join(s) # '123'
5
s = int(s) # 123
6
return s
7
8
9
# How I'd probably write it:
10
def magic(numList):
11
s = ''.join(map(str, numList))
12
return int(s)
13
14
15
# As a one-liner
16
num = int(''.join(map(str,numList)))
17
18
19
# Functionally:
20
s = reduce(lambda x,y: x+str(y), numList, '')
21
num = int(s)
22
23
24
# Using some oft-forgotten built-ins:
25
s = filter(str.isdigit, repr(numList))
26
num = int(s)
27