1

According to this post How to define two-dimensional array in python ,

we can create one two-dimensional array var

Matrix = [[0 for x in range(5)] for x in range(5)]

or

numpy.zeros((5, 5))

It seems the type of value in this matrix is same. Am I right?

Now, I want one matrix like

matrix = 
[[ 0, ['you', 'are', 'here']],
 [ 1, ['you', 'are', 'here']],
 ...
]

Also can get the result of the column 0 is [0, 1, ...], and column 1 is [['you', 'are', 'here'], ['you', 'are', 'here']].

Is that possible in Python? If so, how to implement it efficiently?

Community
  • 1
  • 1
zangw
  • 43,869
  • 19
  • 177
  • 214

1 Answers1

3

You can use np.repeat and array.T method :

>>> 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)
>>> 

Or in python use itertools.repreat and 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)
Mazdak
  • 105,000
  • 18
  • 159
  • 188