python - 当我尝试从 QString 数组创建时,创建 numpy 数组失败

标签 python numpy pyqt4

如果数组的大小为 2x2 或更大,一切都很好,但如果行的维度为 1,例如 1x2,numpy 会做一些我没有预料到的事情。

我该如何解决这个问题?

# TEST 1 OK
myarray = np.array([[QString('hello'), QString('world')],
                    [QString('hello'), QString('moon')]],
                   dtype=object)
print myarray
print myarray.shape
#[[PyQt4.QtCore.QString(u'hello') PyQt4.QtCore.QString(u'world')]
# [PyQt4.QtCore.QString(u'hello') PyQt4.QtCore.QString(u'moon')]]
#(2, 2)


# TEST 2 OK
myarray = np.array([['hello'], ['world']], dtype=object)
print myarray
print myarray.shape  
#[['hello']
# ['world']]
#(2, 1)


# TEST 3 FAIL
myarray = np.array([[QString('hello'), QString('world')]], dtype=object)
print myarray
print myarray.shape
#[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[PyQt4.QtCore.QString(u'h')]]]]]]]]]]]]]]]]]]]]]]]]]]]]]
#..
#[[[[[[[[[[[[[[[[[[[[[[[[[[[[[PyQt4.QtCore.QString(u'e')]]]]]]]]]]]]]]]]]]]]]]]]]]]]]
# etc...
#(1, 2, 5, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)

最佳答案

尝试不同长度的字符串:

np.array([[QString('hello'), QString('moon')]], dtype=object)`.  

或者创建和填充对象数组的方法

A = np.empty((1,2), dtype=object)
A[:] = [QString('hello'), QString('moon')]

我不熟悉这些对象,但在我们尝试从列表构建对象数组的其他情况下,如果列表的长度相同,那就很棘手了。如果 QString 是可迭代的,使用 .__len__ 可能会发生类似的事情。

我猜您的第一个示例之所以有效,是因为 QString 比其他示例短,而不是因为它是 2x2。

这个最近关于从自定义字典类制作对象数组的问题可能是相关的:Override a dict with numpy support

关于python - 当我尝试从 QString 数组创建时,创建 numpy 数组失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36931732/

相关文章:

Python删除CSV文件末尾的空格

python - Python中scipy/numpy中的exp溢出?

python - 将数组写入文本文件

python - python中的过程矩阵

python - pyqt4 qlabel中的背景图片

python - 使用 Python、Phantomjs/PyQt/Ghost 将 URL 转换为 PDF

python - 在 Django Model 数据库函数中使用 Unaccent

python - 由于 reticulate_python,部署 shiny 应用程序时出现问题

python - 元组和字典的优先队列

c++ - 如何在 QTableView 中设置特定单元格的线条样式?