且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将多个整数的列表转换为单个整数?

更新时间:2023-02-10 15:38:39

如果你有一个 int 的列表,你想要的要将它们连接在一起,您可以使用 map $使用 str获得c $ c> 将它们转换为字符串,在空字符串上加入然后再转换回 int 使用 int $ c> s $ c>



在代码中,这看起来像这样:

  r = int(。join(map(str,x)))

r 现在的所需值为 135



int s(作为你的样本)或代表 int s的字符串之外别无其他,否则转换为字符串的步骤可能会失败,或者(负)数字的加入将是笨重的。

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

x=[1, 3, 5]

to an int of 135 (a whole int)?

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.