A note of a trick I used when running a python script in pypy. pypy is a different python execution system for fast execution of python script. This guy is certainly fast. However, the compatibility between pypy and numpy is extremely bad. Recently, although install and import itself pass smoothly, the calculation by numpy in question becomes extremely slow. Some people give up on pypy because it doesn't make sense, so let's deal with array operations that don't use numpy.
First of all, just addition of lists
array1 = [4,5,6]
array2 = [1,2,3]
array_add = list(map(lambda x,y: x+y, array1, array2))
#[5,7,9]
To explain lambda is a convenient one when you want to create a function easily. In the above example, we are creating a function that adds and returns x and y with two arguments. On the other hand, map () takes an array with the function as the first argument and the argument of the first function as the second and subsequent arguments, and applies the elements in the array to the function in order. Will give you. In other words, (4,1), (5,2), (6,3) are passed to the function created by lambda in order for (x, y), and the sum that is the return value is calculated. .. For map (), tuple is the return value in python2. Series, but iter is the return value in python3. Series, so it is recommended to enclose it in list () so that it works in both 2. and 3. Similarly
#subtraction array_subtract = list(map(lambda x,y: x-y, array1, array2)) #[3,3,3]
#multiplication array_multiple = list(map(lambda x,y: x*y, array1, array2)) #[4,10,18]
#division array_div = list(map(lambda x,y: x/y, array1, array2))
If you apply the one-dimensional case, you can add, subtract, multiply, and divide multidimensional arrays without using numpy.
array1 = [[1,2,3],[1,2,3]]
array2 = [[2,3,4],[2,3,4]]
array_add = list(map(lambda x,y: list(map(lambda a,b: a+b, x,y)), array1, array2))
#[[3, 5, 7], [3, 5, 7]]
And, if you make full use of map and lambda without using numpy like this, the operation between arrays is awkward. Even if you don't use pypy, please use it when you don't have to import numpy.
Transpose of a two-dimensional array is often used in addition to arithmetic.
array1 = [[1,2,3],[3,4,5],[6,7,8]]
array1_t = list(zip(*array1))
#[(1,3,6),(2,4,7),(3,5,8)]
Recommended Posts