将整数转换为数字列表 [英] Converting integer to digit list

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

问题描述

integer转换为list的最快,最简洁的方法是什么?

What is the quickest and cleanest way to convert an integer into a list?

例如,将132更改为[1,3,2],将23更改为[2,3].我有一个变量,它是int,并且我希望能够比较各个数字,因此我认为最好将其放入列表中,因为我可以执行int(number[0])int(number[1])来轻松转换将该元素返回到int以进行数字运算.

For example, change 132 into [1,3,2] and 23 into [2,3]. I have a variable which is an int, and I want to be able to compare the individual digits so I thought making it into a list would be best, since I can just do int(number[0]), int(number[1]) to easily convert the list element back into int for digit operations.

推荐答案

首先将整数转换为字符串,然后使用map在其上应用int:

Convert the integer to string first, and then use map to apply int on it:

>>> num = 132
>>> map(int, str(num))    #note, This will return a map object in python 3.
[1, 3, 2]

或使用列表理解:

>>> [int(x) for x in str(num)]
[1, 3, 2]

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

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