在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]