将数字写入数组 [英] Write the digits of a number into an array

查看:155
本文介绍了将数字写入数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用一个很长的数字分开的数字来计算.如何在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?

推荐答案

您可以使用 map int str 这样的函数

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆