In [8]: import numpy as np
In [9]: a = np.array([1,2,3,4,5])
In [10]: int("".join(map(str, a)))
Out[10]: 12345
Answer from Akavall on Stack OverflowHello so I want my input to be an integer of 6 numbers β123456β but then print them out as 3 arrays with two integer each f.e. β12β, β34β, β56β. Any idea which way is the easiest?
In [8]: import numpy as np
In [9]: a = np.array([1,2,3,4,5])
In [10]: int("".join(map(str, a)))
Out[10]: 12345
Just use the sum() function with a generator:
>>> sum(e * 10 ** i for i, e in enumerate(x[::-1]))
12345
or, alternatively:
>>> sum(e * 10 ** (len(x) - i-1) for i, e in enumerate(x))
12345
or you could use str.join, again with a generator:
>>> int(''.join(str(i) for i in x))
12345
why?
In the first example, we use a generator to yield each number multiplied by 10 to the power of its position in the array, we then add these together to get our final result. This may be easier to see if we use a list-comprehension, rather than a generator to see what is going on:
>>> [e * 10 ** i for i, e in enumerate(x[::-1])]
[5, 40, 300, 2000, 10000]
and then it is clear from here that, through summing these numbers together, we will get the result of 12345. Note, however, that we had to reverse x before using this, as otherwise the numbers would be multiplied by the wrong powers of 10 (i.e. the first number would be multiplied by 1 rather than 10000).
In the second snippet, the code simply uses a different method to get the right power of 10 for each index. Rather than reversing the array, we simply subtract the index from the length of x (len(x)), and minus one more so that the first element is 10000, not 100000. This is simply an alternative.
Finally, the last method should be fairly self-explanatory. We are merely joining together the stringified versions of each number in the array, and then converting back to an int to get our result.
python - Write the digits of a number into an array - Stack Overflow
Convert list or numpy array of single element to float in python - Stack Overflow
Python: How do I convert an array of strings to an array of numbers? - Stack Overflow
python - Convert a number to a list of integers - Stack Overflow
Videos
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
You can also use a list comprehension link this.
array = [int(x) for x in str(number)]
You may want to use the ndarray.item method, as in a.item(). This is also equivalent to (the now deprecated) np.asscalar(a). This has the benefit of working in situations with views and superfluous axes, while the above solutions will currently break. For example,
>>> a = np.asarray(1).view()
>>> a.item() # correct
1
>>> a[0] # breaks
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: too many indices for array
>>> a = np.asarray([[2]])
>>> a.item() # correct
2
>>> a[0] # bad result
array([2])
This also has the benefit of throwing an exception if the array is not actually a scalar, while the a[0] approach will silently proceed (which may lead to bugs sneaking through undetected).
>>> a = np.asarray([1, 2])
>>> a[0] # silently proceeds
1
>>> a.item() # detects incorrect size
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: can only convert an array of size 1 to a Python scalar
Just access the first item of the list/array, using the index access and the index 0:
>>> list_ = [4]
>>> list_[0]
4
>>> array_ = np.array([4])
>>> array_[0]
4
This will be an int since that was what you inserted in the first place. If you need it to be a float for some reason, you can call float() on it then:
>>> float(list_[0])
4.0
Use int which converts a string to an int, inside a list comprehension, like this:
desired_array = [int(numeric_string) for numeric_string in current_array]
List comprehensions are the way to go (see @sepp2k's answer). Possible alternative with map:
list(map(int, ['1','-1','1']))
If you are not satisfied with lists (because they can contain anything and take up too much memory) you can use efficient array of integers:
import array
array.array('i')
See here
If you need to initialize it,
a = array.array('i',(0 for i in range(0,10)))
two ways:
x = [0] * 10
x = [0 for i in xrange(10)]
Edit: replaced range by xrange to avoid creating another list.
Also: as many others have noted including Pi and Ben James, this creates a list, not a Python array. While a list is in many cases sufficient and easy enough, for performance critical uses (e.g. when duplicated in thousands of objects) you could look into python arrays. Look up the array module, as explained in the other answers in this thread.