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 OverflowIn [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.
What i want to say is that how can we turn a list/ array like [1,2,3] into a number like 123 also i would love to know how can we turn it back to list.
If you can share the code and explain it would be appreciated.
Python: Convert array into integer - Stack Overflow
python - convert array([[ number ]]) to 'number' - Stack Overflow
python - Convert list of ints to one number? - Stack Overflow
Convert list or numpy array of single element to float in python - Stack Overflow
numpy.astype returns a copy of the array. It does not manipulate your array in-place. So you have to assign the value to a variable:
Y = Y.astype(int)
Ok, if we have numpy here and something like that:
Y = np.array([5., 0., 4., 1., 9.])
We can convert each element of array to int like this:
map(int, Y)
To get this result:
[5, 0, 4, 1, 9]
For Python3+, int has a method for this
Use with AI>>> A=[0xaa, 0xbb, 0xcc]
>>> hex(int.from_bytes(A, byteorder="big"))
'0xaabbcc'
>>> 0xaabbcc == int.from_bytes(A, byteorder="big")
True
For Python2, it's probably best to write a small function
Use with AI>>> A = [0xaa, 0xbb, 0xcc]
>>>
>>> def to_hex(arr):
... res = 0
... for i in arr:
... res <<= 8
... res += i
... return res
...
>>> 0xaabbcc == to_hex(A)
True
Use hex(), map(), and join().
Use with AI>>> '0x' + ''.join(map(hex, A)).replace('0x', '')
'0xaabbcc'
Or with lambda:
Use with AI>>> '0x' + ''.join(map(lambda x: hex(x)[2:], A))
'0xaabbcc'
Thanks to @John La Rooy for pointing out that this fails with 1-digit numbers. The following modification of the lambda version is better:
Use with AI>>> B = [0x1, 0x4, 0x3]
>>> '0x' + ''.join(map(lambda x: hex(x)[2:].rjust(2, '0'), B))
'0x010403'
But at that point it's better to use John's answer.
In [24]: x=np.array([[0.04816103]])
In [25]: x
Out[25]: array([[0.04816103]])
In [26]: x.shape
Out[26]: (1, 1)
In [27]: x[0,0]
Out[27]: 0.04816103
In [28]: x[0][0]
Out[28]: 0.04816103
In [29]: x.squeeze()
Out[29]: array(0.04816103)
In [30]: _.shape
Out[30]: ()
In [34]: x.item()
Out[34]: 0.04816103
I used as this instruction, make two parameters referee one to another as below:
Rad[i] = {'j': str(JY[:, :, 0][0][0]), 'h': str(JY[:, :, 0][0][0] + 1j * JY[:, :,2][0][0])}
Output is:
{'j': '0.04816103', 'h': '(5.21626177-5.11993971j)'}
# Over-explaining a bit:
def magic(numList): # [1,2,3]
s = map(str, numList) # ['1','2','3']
s = ''.join(s) # '123'
s = int(s) # 123
return s
# How I'd probably write it:
def magic(numList):
s = ''.join(map(str, numList))
return int(s)
# As a one-liner
num = int(''.join(map(str,numList)))
# Functionally:
s = reduce(lambda x,y: x+str(y), numList, '')
num = int(s)
# Using some oft-forgotten built-ins:
s = filter(str.isdigit, repr(numList))
num = int(s)
Two solutions:
>>> nums = [1, 2, 3]
>>> magic = lambda nums: int(''.join(str(i) for i in nums)) # Generator exp.
>>> magic(nums)
123
>>> magic = lambda nums: sum(digit * 10 ** (len(nums) - 1 - i) # Summation
... for i, digit in enumerate(nums))
>>> magic(nums)
123
The map-oriented solution actually comes out ahead on my box -- you definitely should not use sum for things that might be large numbers:

import collections
import random
import timeit
import matplotlib.pyplot as pyplot
MICROSECONDS_PER_SECOND = 1E6
FUNS = []
def test_fun(fun):
FUNS.append(fun)
return fun
@test_fun
def with_map(nums):
return int(''.join(map(str, nums)))
@test_fun
def with_interpolation(nums):
return int(''.join('%d' % num for num in nums))
@test_fun
def with_genexp(nums):
return int(''.join(str(num) for num in nums))
@test_fun
def with_sum(nums):
return sum(digit * 10 ** (len(nums) - 1 - i)
for i, digit in enumerate(nums))
@test_fun
def with_reduce(nums):
return int(reduce(lambda x, y: x + str(y), nums, ''))
@test_fun
def with_builtins(nums):
return int(filter(str.isdigit, repr(nums)))
@test_fun
def with_accumulator(nums):
tot = 0
for num in nums:
tot *= 10
tot += num
return tot
def time_test(digit_count, test_count=10000):
"""
:return: Map from func name to (normalized) microseconds per pass.
"""
print 'Digit count:', digit_count
nums = [random.randrange(1, 10) for i in xrange(digit_count)]
stmt = 'to_int(%r)' % nums
result_by_method = {}
for fun in FUNS:
setup = 'from %s import %s as to_int' % (__name__, fun.func_name)
t = timeit.Timer(stmt, setup)
per_pass = t.timeit(number=test_count) / test_count
per_pass *= MICROSECONDS_PER_SECOND
print '%20s: %.2f usec/pass' % (fun.func_name, per_pass)
result_by_method[fun.func_name] = per_pass
return result_by_method
if __name__ == '__main__':
pass_times_by_method = collections.defaultdict(list)
assert_results = [fun([1, 2, 3]) for fun in FUNS]
assert all(result == 123 for result in assert_results)
digit_counts = range(1, 100, 2)
for digit_count in digit_counts:
for method, result in time_test(digit_count).iteritems():
pass_times_by_method[method].append(result)
for method, pass_times in pass_times_by_method.iteritems():
pyplot.plot(digit_counts, pass_times, label=method)
pyplot.legend(loc='upper left')
pyplot.xlabel('Number of Digits')
pyplot.ylabel('Microseconds')
pyplot.show()
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
Hello 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?