This question already has an answer here:
- Splitting integer in Python? 10 answers
I want to make a number , for example 43365644 into single numbers [4,3,3....,4,4]
and append it on a list
This can be done quite easily if you:
Use
strto convert the number into a string so that you can iterate over it.Use a list comprehension to split the string into individual digits.
Use
intto 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]
>>>
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]
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.
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