在Python中将整数转换为数字列表 [英] Converting integer to digit list in Python
本文介绍了在Python中将整数转换为数字列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
将整数
转换为列表
的最快捷,最简洁的方法是什么?
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]
这篇关于在Python中将整数转换为数字列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文