Abdulla Dlshad Abdulla Dlshad - 21 days ago 8
Python Question

How to convert array elements to integer in Python

I am trying to implement rsa algorithm. So, I would like to combine array elements based on block size. For example:

blockSize = 2
arr = [1, 3, 45, 6, 2, 90, 103]


I am willing to merge the elements in a way that 1st and 2nd will be combined into one element. so the array would look like this:

arr = [13, 456, 290, 103]

Answer

Divide to chunks by block_size, then map all the values in each cell to strings, the join the strings and convert them to integer:

new_arr = [int(''.join(map(str, arr[i: i+block_size]))) for i in range(0, len(arr), block_size)]

More detailed overview on the chunks convertion:

int(''.join(map(str, arr[i: i+block_size])))
                     arr[i: i+block_size]      for every chunk
            map(str, ....................)     map every number in the chunks to string
    ''.join(..............................)    join these strings
int(.......................................)   convert the join string to integer
Comments