How to convert a list of multiple integers into a single integer?

前端 未结 4 883
鱼传尺愫
鱼传尺愫 2021-01-11 09:02

How do I convert a list in Python 3.5 such as:

x=[1, 3, 5]

to an int of 135 (a whole int)?

4条回答
  •  囚心锁ツ
    2021-01-11 09:54

    Here is a more mathematical way that does not have to convert back and forth to string. Note that it will only work if 0 <= i <= 9.

    >>> x = [1, 3, 5]
    >>> sum(d * 10**i for i, d in enumerate(x[::-1]))
    135
    

    The idea is to multiply each element in the list by its corresponding power of 10 and then to sum the result.

提交回复
热议问题