Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/279.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Python中定义一个具有不同列值类型的矩阵或二维数组,并高效地检索该列_Python_Arrays_Matrix - Fatal编程技术网

如何在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)