将整数列表转换为一个数字?
问题描述:
我有一个整数列表,我想将其转换为一个数字,例如:
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'>
实现magic 功能的最佳方法是什么?
What is the best way to implement the magic function?
编辑
我确实找到了 this,但似乎必须有更好的方法.
EDIT
I did find this, but it seems like there has to be a better way.
答
# 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)