Turn a single number into single digits Python [duplicate]

℡╲_俬逩灬. 提交于 2019-12-17 18:36:34

问题


I want to make a number , for example 43365644 into single numbers [4,3,3....,4,4]

and append it on a list


回答1:


This can be done quite easily if you:

  1. Use str to convert the number into a string so that you can iterate over it.

  2. Use a list comprehension to split the string into individual digits.

  3. Use int to convert the digits back into integers.

Below is a demonstration:

>>> n = 43365644
>>> [int(d) for d in str(n)]
[4, 3, 3, 6, 5, 6, 4, 4]
>>>



回答2:


Here's a way to do it without turning it into a string first (based on some rudimentary benchmarking, this is about twice as fast as stringifying n first):

>>> n = 43365644
>>> [(n//(10**i))%10 for i in range(math.ceil(math.log(n, 10))-1, -1, -1)]
[4, 3, 3, 6, 5, 6, 4, 4]



回答3:


The easiest way is to turn the int into a string and take each character of the string as an element of your list:

>>> n = 43365644 
>>> digits = [int(x) for x in str(n)]
>>> digits
[4, 3, 3, 6, 5, 6, 4, 4]
>>> lst.extend(digits)  # use the extends method if you want to add the list to another

It involves somes casting operation, but it's readable and acceptable if you doesn't need extreme performance.




回答4:


If you want to change your number into a list of those numbers, I would first cast it to a string, then casting it to a list will naturally break on each character:

[int(x) for x in str(n)]


来源:https://stackoverflow.com/questions/21270320/turn-a-single-number-into-single-digits-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!