如何在Python中定义一个具有不同列值类型的矩阵或二维数组,并高效地检索该列
根据这篇文章 , 我们可以创建一个二维数组如何在Python中定义一个具有不同列值类型的矩阵或二维数组,并高效地检索该列,python,arrays,matrix,Python,Arrays,Matrix,根据这篇文章 , 我们可以创建一个二维数组 Matrix = [[0 for x in range(5)] for x in range(5)] 或 numpy.zero((5,5)) 这个矩阵中的值类型似乎是相同的我说得对吗? 现在,我想要一个像这样的矩阵 matrix = [[ 0, ['you', 'are', 'here']], [ 1, ['you', 'are', 'here']], ... ] 还可以获得列0的结果是[0,1,…],而列1是[['you','are','h
Matrix = [[0 for x in range(5)] for x in range(5)]
或
numpy.zero((5,5))
这个矩阵中的值类型似乎是相同的我说得对吗?
现在,我想要一个像这样的矩阵
matrix =
[[ 0, ['you', 'are', 'here']],
[ 1, ['you', 'are', 'here']],
...
]
还可以获得列0
的结果是[0,1,…]
,而列1
是[['you','are','here'],['you','are','here']]
这在Python中是否可能?如果是这样,如何有效地实现它?您可以使用
np。重复和array.T
方法:
>>> np.array((np.arange(N),np.repeat([test],N,axis=0)),dtype=object).T
array([[0, array(['you', 'are', 'here'],
dtype='|S4')],
[1, array(['you', 'are', 'here'],
dtype='|S4')],
[2, array(['you', 'are', 'here'],
dtype='|S4')],
[3, array(['you', 'are', 'here'],
dtype='|S4')],
[4, array(['you', 'are', 'here'],
dtype='|S4')],
[5, array(['you', 'are', 'here'],
dtype='|S4')],
[6, array(['you', 'are', 'here'],
dtype='|S4')],
[7, array(['you', 'are', 'here'],
dtype='|S4')],
[8, array(['you', 'are', 'here'],
dtype='|S4')],
[9, array(['you', 'are', 'here'],
dtype='|S4')]], dtype=object)
>>>
或者在python中使用itertools.repreat
和zip
:
>>> from itertools import repeat
>>> N=10
>>> test=['you', 'are', 'here']
>>>
>>> np.array(zip(range(N),repeat(test,N)),dtype=object)
array([[0, ['you', 'are', 'here']],
[1, ['you', 'are', 'here']],
[2, ['you', 'are', 'here']],
[3, ['you', 'are', 'here']],
[4, ['you', 'are', 'here']],
[5, ['you', 'are', 'here']],
[6, ['you', 'are', 'here']],
[7, ['you', 'are', 'here']],
[8, ['you', 'are', 'here']],
[9, ['you', 'are', 'here']]], dtype=object)