如何有效地将C / C++逻辑转换为python?
How to Efficiently convert C/C++ logic into python?
我有一个.cpp代码,如下所示,其中我正在将一些matrix_1值复制到matrix_2。
(注:最初matrix_2是matrix_1的副本。
num_of_row_of_matrix_1 = 400
num_of_col_of_matrix_1 = 700
for (int Row = 0; Row < num_of_row_of_matrix_1; Row += 2)
{
for (int Col = 0; Col < num_of_col_of_matrix_1; Col += 2)
{
matrix_2[Row + 1][Col] = matrix_1[Row][Col + 1];
}
}
现在我在 python-2.7 中实现的相同代码如下所示,
for Row in range(len(matrix_1)/2):
Row *= 2
for Col in range(len(matrix_1[0])/2):
Col *= 2
matrix_2[Row + 1, Col] = matrix_1[Row, Col + 1]
python中的矩阵就像
array([[1, 2, 3, ..., 33, 37, 36],
[4, 5, 6, ..., 25, 16, 26],
[2, 4, 7, ..., 37, 32, 36],
...,
[ 35, 106, 36, ..., 151, 37, 141],
[114, 179, 119, ..., 2, 165, 133],
[ 37, 111, 34, ..., 144, 39, 139]], dtype=uint8)
python 中的转换速度比 cpp 慢约 4 倍。
有没有有效的方法可以在python中做同样的事情?
如果您需要更多信息以进行澄清,请告诉我。
看起来这些是 NumPy 数组。如果是这样,你可以做
matrix_2[1::2, ::2] = matrix_1[::2, 1::2]
以避免 Python 级循环和包装器对象构造的开销。
for Row in range(len(matrix_1)/2):
Row *= 2
for Col in range(len(matrix_1[0])/2):
Col *= 2
matrix_2[Row + 1, Col] = matrix_1[Row, Col + 1]
实际上,上面的代码是我在一个函数中编写的,我一次又一次地调用。我问了这个问题来改进它。
在此代码中,反复调用此matrix_2[Row + 1, Col] = matrix_1[Row, Col + 1]
非常耗时,这只不过是检查索引并复制到另一个矩阵。
x = np.arange (0, num_of_row_of_matrix_1*num_of_col_of_matrix_1).reshape(num_of_row_of_matrix_1, num_of_col_of_matrix_1)
h1, w1 = np.where (np.logical_and ( ((x/num_of_col_of_matrix_1)%2 == 0), (x%2 == 1)))
h2, w2 = np.where (np.logical_and ( ((x/num_of_col_of_matrix_1)%2 == 1), (x%2 == 0)))
这给了我必须复制的内容的索引。由于这些索引是固定的,我需要复制,所以我把它放在函数之外。然后,在函数中,我只是复制选定的索引,例如matrix_2[h2, w2] = matrix_1[h1, w1]
不需要时间。
- 如何将真正的字符串从python c-api转换为python脚本
- 如何在C++中将 Python 字符串转换为其转义版本?
- 使用转换器提升 Python 问题 - 静态链接
- 如何将 Python 双端转换为C++容器?
- 如何将 c++ get 函数代码转换为 opencv 算法中使用的 python
- 将Wiimote MAC地址转换为PIN码,从C++转换为Python或Javascript
- 将代码从 Python 转换为 C++ 时出错
- 将 c++ 代码转换为 python,使用运算符?
- 如何将二进制文件头示例代码 (C++/C#) 转换为 Python?
- 在 c++ 中逐行读取文件(将代码从 Python 转换为 C++)
- 如何大致将 cpp 代码结构转换为 python
- 从从该抽象类派生的 Python 对象强制转换C++抽象类C++
- 将数学函数从 Python 转换为 c++
- 从Python转换为C++
- 如何将python的for循环转换为c++
- 如何将OpenCV图像数据从Python转换为C++?
- 如何将 Python 对象转换为 Cython 扩展类型的 std::vector 并返回?
- 从 std::vector<double> 到 Python 列表的转换失败(提升 python)
- 如何在C (转换Python代码)中引用一个函数
- 编织内联类型转换(python)