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

前端 未结 4 951
鱼传尺愫
鱼传尺愫 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 10:04

    If you have a list of ints and you want to join them together, you can use map with str to convert them to strings, join them on the empty string and then cast back to ints with int.

    In code, this looks like this:

    r = int("".join(map(str, x)))
    

    and r now has the wanted value of 135.

    This, of course, is a limited approach that comes with some conditions. It requires the list in question to contain nothing else but positive ints (as your sample) or strings representing ints, else the steps of conversion to string might fail or the joining of (negative) numbers will be clunky.

提交回复
热议问题