假设我有一本__array_interface__字典,我想从字典本身创建该数据的 numpy 视图。例如:
buff = {'shape': (3, 3), 'data': (140546686381536, False), 'typestr': '<f8'}
view = np.array(buff, copy=False)
Run Code Online (Sandbox Code Playgroud)
但是,这不适用于np.array将缓冲区或数组接口作为属性进行搜索。简单的解决方法可能如下:
class numpy_holder(object):
pass
holder = numpy_holder()
holder.__array_interface__ = buff
view = np.array(holder, copy=False)
Run Code Online (Sandbox Code Playgroud)
这看起来有点绕。我是否缺少一种直接的方法来做到这一点?
我最近一直在尝试用C++编写一个函数,它将双精度矢量转换为字符串矢量.我想从python解释器运行它,所以我使用Pybind11来连接C++和Python.这是我到目前为止,
#include <pybind11/pybind11.h>
#include <boost/lexical_cast.hpp>
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <vector>
std::string castToString(double v) {
std::string str = boost::lexical_cast<std::string>(v);
return str;
}
std::vector<std::vector<std::string> > num2StringVector(std::vector<std::vector<double> >& inputVector) {
//using namespace boost::multiprecision;
std::vector<std::vector<std::string> > outputVector;
std::transform(inputVector.begin(), inputVector.end(), std::back_inserter(outputVector), [](const std::vector<double> &iv) {
std::vector<std::string> dv;
std::transform(iv.begin(), iv.end(), std::back_inserter(dv), &castToString);
return dv;
});
return outputVector;
}
namespace py = pybind11;
PYBIND11_PLUGIN(num2String) {
py::module m("num2String", "pybind11 example plugin");
m.def("num2StringVector", &num2StringVector, "this converts a vector of doubles to a vector of strings.");
m.def("castToString", …Run Code Online (Sandbox Code Playgroud) 我只是安装了 pybinding,我正在尝试运行这个库的文档中提出的第一个示例。
import pybinding as pb
import numpy as np
import matplotlib.pyplot as plt
import pybinding as pb
d = 0.2 # [nm] unit cell length
t = 1 # [eV] hopping energy
# create a simple 2D lattice with vectors a1 and a2
lattice = pb.Lattice(a1=[d, 0], a2=[0, d])
lattice.add_sublattices(
('A', [0, 0]) # add an atom called 'A' at position [0, 0]
)
lattice.add_hoppings(
# (relative_index, from_sublattice, to_sublattice, energy)
([0, 1], 'A', 'A', t),
([1, 0], 'A', 'A', …Run Code Online (Sandbox Code Playgroud)