简体   繁体   中英

python performance loop vs. sum vs. exec

The question to compare the performance of sum and loop I did find - but I have a second level question:

There is a 2 dimensional array 'board' that holds integers and a list 'cells' with references to the single elements.

This list is stable.

I do have to sum the elements which I do using a loop:

r = w
for cell in cells:
    r += board[cell[0]][cell[1]]

as I have to do this several times (with changing values) I am looking for the most performant way..

Already thanks for any answers.

jGda

Convert your board to a numpy array, then you can index select the needed values and use numpys fast sum function.

numpy_board = np.array(board)
your_sum = numpy_board[cells[0], cells[1]].sum()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM