将三位数整数拆分为Python中每个数字的三项列表

时间:2011-09-02 10:17:12

标签: python

我是Python的新手。我想要做的是采用像634这样的三位数整数,并将其拆分,使其成为一个三项列表,即

digits = [ 6, 3, 4 ]

非常感谢任何帮助。

8 个答案:

答案 0 :(得分: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]

答案 1 :(得分: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

答案 2 :(得分:5)

转换为字符串,将字符串视为列表并转换回int:

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

答案 3 :(得分:3)

或者,您可以使用十进制模块执行此操作:

>>> from decimal import Decimal
>>> Decimal(123).as_tuple()
DecimalTuple(sign=0, digits=(1, 2, 3), exponent=0)
>>> Decimal(123).as_tuple().digits
(1, 2, 3)

...也适用于实数......

>>> Decimal(1.1).as_tuple()
DecimalTuple(sign=0, digits=(1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 8, 1, 7, 8, 4, 1, 9, 7, 0, 0, 1, 2, 5, 2, 3, 2, 3, 3, 8, 9, 0, 5, 3, 3, 4, 4, 7, 2, 6, 5, 6, 2, 5), exponent=-51)
>>> Decimal('1.1').as_tuple()
DecimalTuple(sign=0, digits=(1, 1), exponent=-1)

答案 4 :(得分:1)

像这样:

Python2> i = 634
Python2> digits = [int(d) for d in list(str(i))]
Python2> digits
[6, 3, 4]

这会将int转换为字符串,将字符分成列表,然后将列表映射回整数(使用列表解析)。

答案 5 :(得分:1)

要在不转换为字符串的情况下执行此操作(并且不使用日志作弊以查看将有多少位数),请使用重复调用divmod:

>>> digits = []
>>> value = 634
>>> while value: value,b = divmod(value,10); digits.insert(0,b)
...
>>> digits
[6, 3, 4]

答案 6 :(得分:0)

您可以使用此功能将任何数字转换为十进制数字列表:

def todigits(n):
    return map(int, list(str(n)))

或者这个恰恰相反:

def fromdigits(lst):
    return int("".join(map(str, lst)))

答案 7 :(得分:0)

num = 153

while num > 0:
    digit = num % 10
    print(digit)
    num //= 10