将数字写入数组 [英] Write the digits of a number into an array
问题描述
我想用一个很长的数字分开的数字来计算.如何在Python2.7中做到这一点?我考虑过以某种方式将数字写入数组,以便可以使用array(x)访问数字:
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
函数将number
转换为字符串.
str
function converts the number
to a string.
map
函数将int
函数应用于字符串化数字的每个元素,以将字符串转换为整数.
map
function applies the int
function to each and every element of stringifed number, to convert the string to an integer.
输出
[1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9]
如果您一次又一次地执行此操作(例如循环执行),则列表理解将比map
方法快
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")
我的机器上的输出
12.8388962786
10.7739010307
这篇关于将数字写入数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!