我有一个整数列表,我想将其转换为一个数字,例如:
numList = [1, 2, 3]
num = magic(numList)
print num, type(num)
>>> 123, <type 'int'>
实现magic功能的最佳方式是什么?
编辑
我确实找到了 this ,但似乎必须有更好的方法。
最佳答案
# 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)
关于python - 将整数列表转换为一个数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/489999/