I got a line of code from the net that works correctly, but I don't know how

import numpy as np
randomArray= np.random.uniform(1, 100, size=(5,5))
columnSumm= list(map(sum,zip(*randomArray)))
print(randomArray, columnSumm)

Please explain the third line of code in detail, in plain language.

  • Answer # 1

    zip(*my_list)is a well-known trick in Vanilla Python to transpose a matrix (a list of lists).


    In [56]: lst= [[1,2], [3,4]]
    In [57]: list(zip(*lst))
    Out[57]: [(1, 3), (2, 4)]

    But since you're already using Numpy, why not take advantage of its fast and optimized methods:

    In [62]: randomArray.sum(axis=0)
    array([343.75311042, 216.14459965, 300.61339319, 128.05807225,
    In[63]: columnSumm

    for large Numpy arrays, the code will run orders of magnitude faster

  • Answer # 2

    You are creating an array of size5 by 5with random numbers from 1 to 100, then create a new array1 to 5from the sums of each column.

    list-list creation

    Functionmap()is used to apply a function to each element of an iterable object (such as a list or dictionary) and return a new iterator to get the results

    sum-Summarizes the elements of the specified object and returns the result.

    functionzipallows you to walk through several iterable objects (lists, etc.)

    In my case, zip goes through each line of the array?

    Spenkau2022-02-14 07:10:52

    yes, in this case it is passed through the columns because of the pre-created list. go through the print on each step and you will understand everything, start with print(list(randomArray)) and so on

    tomato-magnet-regulato2022-02-14 07:33:46