简体   繁体   中英

create an array or list with different element sizes python

I would like to create an array or list with different element size however, I got the output not as expected with a word array written in the middle of the array as in the following:

import numpy as np
lst_2=np.array([1,2,np.repeat(3,3),2],dtype="object")
print(lst_2) 
#Output is=[ 1 2 array([3,3,3]) 2]
#lst_2 should be = [1,2,3,3,3,2]...... 

please any help or suggestion

You are mixing lists and numpy arrays. I presume what you want to achieve is a numpy array that looks as follows:

import numpy as np
lst_2=np.concatenate([np.array([1,2]), np.repeat(3,3),[2]])
print(lst_2) 

Output:

[1 2 3 3 3 2]

Alternatively you can also use the following if you want a list:

lst_2 = [1,2] + list(np.repeat(3,3)) + [2]

The plus operator here stands for concatenation of two lists. Whereas the plus operator stands for elementwise addition in case of numpy arrays.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM