如何将多个整数的列表转换为单个整数? [英] How to convert a list of multiple integers into a single integer?

查看:120
本文介绍了如何将多个整数的列表转换为单个整数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Python 3.5中转换列表,例如:

  x = [1,3,5] 

135 的int(整个int) ?

解决方案

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



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

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

r 现在的所需值为 135



<这是合作的urse,是一种有限的方法,有一些条件。它要求有问题的列表除了正 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.

这篇关于如何将多个整数的列表转换为单个整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆