numpy tolist() 不舒服的输出
numpy tolist() uncomfortable output
我正在尝试以列表形式提取 numpy 矩阵的一列。我使用了 tolist()
方法,但它对我的目的没有用。
让我们看看代码。
import numpy as np
def get_values(feature):
'''
This method creates a lst of all values in a feature, without repetitions
:param feature: the feature of which we want to extract values
:return: lst of the values
'''
values = []
for i in feature:
if i not in values:
values.append(i)
return values
lst=[1, 2, 4, 4, 6]
a=get_values(lst)
print(a)
b=np.matrix('1 2; 3 4')
col = b[:,0].tolist()
print(col)
if col == [1, 3]:
print('done!')
输出
[1, 2, 4, 6]
[[1], [3]]
如您所见,方法 tolist()
返回的列表在 if 语句中被忽略。现在,如果我不能更改 if 语句(出于任何原因),我该如何管理 b
就好像它是一个像 a
这样的列表?
问题是 numpy.matrix
对象总是保持二维。转换为数组,然后展平:
>>> col = b[:,0].getA().flatten().tolist()
>>> col
[1, 3]
或者可能只使用正常的 numpy.ndarray
s...
>>> a = b.getA()
>>> a[:,0]
array([1, 3])
对比...
>>> b[:,0]
matrix([[1],
[3]])
我正在尝试以列表形式提取 numpy 矩阵的一列。我使用了 tolist()
方法,但它对我的目的没有用。
让我们看看代码。
import numpy as np
def get_values(feature):
'''
This method creates a lst of all values in a feature, without repetitions
:param feature: the feature of which we want to extract values
:return: lst of the values
'''
values = []
for i in feature:
if i not in values:
values.append(i)
return values
lst=[1, 2, 4, 4, 6]
a=get_values(lst)
print(a)
b=np.matrix('1 2; 3 4')
col = b[:,0].tolist()
print(col)
if col == [1, 3]:
print('done!')
输出
[1, 2, 4, 6]
[[1], [3]]
如您所见,方法 tolist()
返回的列表在 if 语句中被忽略。现在,如果我不能更改 if 语句(出于任何原因),我该如何管理 b
就好像它是一个像 a
这样的列表?
问题是 numpy.matrix
对象总是保持二维。转换为数组,然后展平:
>>> col = b[:,0].getA().flatten().tolist()
>>> col
[1, 3]
或者可能只使用正常的 numpy.ndarray
s...
>>> a = b.getA()
>>> a[:,0]
array([1, 3])
对比...
>>> b[:,0]
matrix([[1],
[3]])