I want to calculate with seperated digits of a very long number. How can I do this in Python2.7? I thought about somehow write the digits in an array so that I can access the digits with array(x):
number = 123456789123456789
array = [1,2,3,4,5,6,7,8,9,1,2,3,4,5,6,7,8,9]
The problem is, that the number has so many digits, that it would take very long to do that manually. So how can I do this automatically?
You can use map
, int
and str
functions like this
print map(int, str(number))
str
function converts the number
to a string.
map
function applies the int
function to each and every element of stringifed number, to convert the string to an integer.
Output
[1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9]
If you are doing this again and again, like in a loop, then list comprehension will be faster than the map
approach
number = 123456789123456789
from timeit import timeit
print timeit("map(int, str(number))", "from __main__ import number")
print timeit("[int(dig) for dig in str(number)]", "from __main__ import number")
Output on my machine
12.8388962786
10.7739010307
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With