python - 将整数列表转换为一个数字?

标签 python

我有一个整数列表,我想将其转换为一个数字,例如:

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/

相关文章:

python - 平滑离散二维坐标

python - 在 python 中重命名、调整大小和移动图像文件

python - 如何禁用flask app.run() 的默认消息?

python - 如何为 Seaborn Heatmap 彩条添加标签?

python - 仅在满足 if 条件后才运行 for 循环

python - DRF : Validate nested serializer data when creating, 但更新时没有

python - 将 Pandas 时间戳插入 Mongodb

python - 从 Django 模型的保存方法中引发 ValidationError?

python - 有效日期范围单热编码 groupby

python - 具有可过滤属性的 Django 模型