在Python中将三位整数分割成包含每个数字的三项列表

9 投票
8 回答
25822 浏览
提问于 2025-04-17 01:13

我刚开始学习Python。我想做的是把一个三位数的整数,比如说634,拆分成一个包含三个元素的列表,也就是:

digits = [ 6, 3, 4 ]

如果有人能帮我解决这个问题,我会非常感激。

8 个回答

5

把数字转换成字符串,然后把这个字符串当成一个列表,最后再把它转换回整数:

In [5]: input = 634
In [6]: digits =[int(i) for i in str(input)]
In [7]: print digits
[6, 3, 4]
8

使用 str() 函数有点懒惰。它的速度比用数学方法要慢很多。如果用 while 循环的话,速度会更快。

In [1]: n = 634

In [2]: timeit [int(i) for i in str(n)]
100000 loops, best of 3: 5.3 us per loop

In [3]: timeit map(int, str(n))
100000 loops, best of 3: 5.32 us per loop

In [4]: import math

In [5]: timeit [n / 10 ** i % 10 for i in range(int(math.log(n, 10)), -1, -1)]
100000 loops, best of 3: 3.69 us per loop

如果你知道这个数字正好是3位数,那你可以做得更快。

In [6]: timeit [n / 100, n / 10 % 10, n % 10]
1000000 loops, best of 3: 672 ns per loop
20

你可以把数字转换成字符串,然后逐个字符地把它们再转换回整数:

>>> [int(char) for char in str(634)]
[6, 3, 4]

或者,正如 @eph 在下面提到的,可以使用 map() 函数:

>>> map(int, str(634))        # Python 2
[6, 3, 4]

>>> list(map(int, str(634)))  # Python 3
[6, 3, 4]

撰写回答