简体   繁体   English

python 性能循环与总和与执行

[英]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:我确实找到了比较 sum 和 loop 性能的问题 - 但我有一个第二级问题:

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 数组,然后您可以索引 select 所需的值并使用 numpys 快速求和 function。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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