python - 高效的矩阵计算算法

标签 python list numpy matrix

除此之外efficient algorithm for list edits我正在寻找一种更有效的算法来进行另一个“循环计算”。 这次我有一个像这样的矩阵:

grid_z1 = [[1,2,3],
           [4,5,6],
           [7,8,9]]

并且用户可以输入多个参数:目标是将矩阵内的值更改为下一个最高的参数值(如果矩阵值高于 max(paramter) 则将其更改为 nan )例如,当用户输入“4”和“7”时,矩阵值“5”应更改为“7”(=输入值的下一个最高值)。 示例:

h = [2, 7, 4] # user entered this three values
grid_z1 = [[2, 2, 4],
           [4, 7, 7],
           [7, nan, nan]] # this should be my output

此外,我想计算更改为给定值的值的数量。在我的示例中,这应该是 [2,2,3] -> 2x2, 2x4, 3x7

h.sort()
h.reverse()

count = [0]*len(h)

for i in range(len(grid_z1)):
    for j in range(len(grid_z1[0])):
        if grid_z1[i][j] > max(h):
            grid_z1[i][j] = float('NaN')
        else:
            for k in range(len(h)-1):
                if grid_z1[i][j] <= h[k] and grid_z1[i][j] > h[k+1]:
                    grid_z1[i][j] = h[k]
                    count[k] += 1
            if grid_z1[i][j] <= min(h):
                grid_z1[i][j] = min(h)
                count[-1] += 1

print grid_z1
print count

但是还是很慢。遗憾的是,我对 zip 方法的理解还不足以将其用于这个更复杂的算法。

最佳答案

使用bisect模块:

from bisect import bisect_left
def solve(matrix, param):
    param.sort()             #Sort the params passed by user
    maxx = param[-1]         #Find max
    for row in matrix:
        # If item in the row is greater than `maxx` then use Nan
        # else use bisect_right to get the next highest item from
        # params in O(log N) time.
        yield [float('nan') if item > maxx else
                                 param[bisect_left(param, item)] for item in row]

grid_z1 = [[1,2,3],
           [4,5,6],
           [7,8,9]]
print list(solve(grid_z1, [2, 7, 4]))   

输出:

[[2, 2, 4], [4, 7, 7], [7, nan, nan]]

关于python - 高效的矩阵计算算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20161770/

相关文章:

python - numpy 中多个向量的逐元素最小值

Python 列表到 Pandas 数据框的字典

java - 在该类的方法体内实例化泛型类

具有很少非零(非常稀疏)的 Python 洗牌数组

python - 将图像复制到剪贴板并保留透明度

python - 如何比较字典中的键并查看一个键是否包含另一个键?

python - Numpy 已安装但仍然出现错误

python - 在Python中为卷积创建nxn边界掩码的优雅方法

Python Selenium 动态表格单元格返回空字符串

python - 如何在python中对日期进行排序?