需要将数据打印成类似python中的numpy
时间: 2024-03-13 19:45:27 浏览: 45
python 的numpy
4星 · 用户满意度95%
要将数据打印成类似Python中的numpy数组格式,可以对上面的递归打印进行修改。具体实现可以参考以下示例代码:
```
#include <iostream>
#include <map>
#include <vector>
#include <typeinfo>
template<typename T>
void print(const T& t, int depth = 0)
{
bool is_leaf = true;
for (auto i : t)
{
if (typeid(i.second).name()[0] != 'N')
{
is_leaf = false;
break;
}
}
if (is_leaf)
{
std::cout << "[";
for (auto i : t)
{
std::cout << i.second << ", ";
}
std::cout << "]" << std::endl;
}
else
{
std::cout << "[" << std::endl;
for (auto i : t)
{
for (int j = 0; j < depth + 1; ++j) std::cout << " ";
std::cout << "[";
std::cout << i.first << ", ";
print(i.second, depth + 1);
for (int j = 0; j < depth + 1; ++j) std::cout << " ";
std::cout << "],";
std::cout << std::endl;
}
for (int j = 0; j < depth; ++j) std::cout << " ";
std::cout << "]" << std::endl;
}
}
int main()
{
std::map<std::string, std::vector<std::map<int, std::string>>> data = {
{"A", {
{
{1, "A1"},
{2, "A2"},
{3, "A3"}
},
{
{4, "A4"},
{5, "A5"},
{6, "A6"}
}
}},
{"B", {
{
{1, "B1"},
{2, "B2"}
},
{
{3, "B3"},
{4, "B4"},
{5, "B5"}
},
{
{6, "B6"}
}
}}
};
print(data);
return 0;
}
```
这段代码会先判断当前层级的数据中是否包含非叶子节点,如果是,则递归打印下一级数据;否则,打印当前层级的所有叶子节点。对于非叶子节点,我们在打印前加上了中括号,并在每个元素前加上了逗号,以便生成类似numpy数组的格式。
阅读全文