开发者

Create a list from a long int

I've got a very long ( 1000 digit ) number. I want to con开发者_JAVA技巧vert it into a list , how would you go about it since :

list(n)

TypeError: 'long' object is not iterable


It's not exactly clear what you're asking for, but if what you want is to iterate over the digits, just convert it to a string:

x = str(n)

You can iterate over a string as if it were a list.

If you really want a true list (only reason I can think of is you want to modify digits), you can do:

xl = list(str(n))

(In the event someone comes along looking for a way to convert an 1000-digit integer into a list of bytes, the answer is... normally don't, it's not really meaningful in most contexts (numbers that big aren't stored/manipulated as typical native data types). If you need to get it into a packed binary form, look into NumPy, which you should probably be using anyway if you're routinely dealing with numbers this large.

If you've got a more typical number (e.g. 8, 16, 32 or 64 bits), check out the included struct module.)


If you want each character in a string representation of the number as a separate list item:

digits = list(str(n))

Note that if you just want to iterate over the characters in the number one at a time, you don't need to make a list. The string itself is iterable:

for d in str(n):
   print d,

If you want each digit (as an integer) as a separate list item, and assuming the number is known to be positive (so as not to have to deal with the pesky minus sign):

digits = [int(d) for d in str(n)]


one way would be list('%d' % mynumber)

Python 2.6.6 (r266:84292, Apr 20 2011, 11:58:30) 
[GCC 4.5.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> n=8948974395274589470928357238945723894572395723572358257
>>> list(n)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'long' object is not iterable
>>> list('%d' % n)
['8', '9', '4', '8', '9', '7', '4', '3', '9', '5', '2', '7', '4', '5', '8', '9', '4', '7', '0', '9', '2', '8', '3', '5', '7', '2', '3', '8', '9', '4', '5', '7', '2', '3', '8', '9', '4', '5', '7', '2', '3', '9', '5', '7', '2', '3', '5', '7', '2', '3', '5', '8', '2', '5', '7']
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜