Create an empty list in python with certain size

后端 未结 15 1741
有刺的猬
有刺的猬 2020-11-22 12:00

I want to create an empty list (or whatever is the best way) that can hold 10 elements.

After that I want to assign values in that list, for example this is supposed

15条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-22 12:30

    I came across this SO question while searching for a similar problem. I had to build a 2D array and then replace some elements of each list (in 2D array) with elements from a dict. I then came across this SO question which helped me, maybe this will help other beginners to get around. The key trick was to initialize the 2D array as an numpy array and then using array[i,j] instead of array[i][j].

    For reference this is the piece of code where I had to use this :

    nd_array = []
    for i in range(30):
        nd_array.append(np.zeros(shape = (32,1)))
    new_array = []
    for i in range(len(lines)):
        new_array.append(nd_array)
    new_array = np.asarray(new_array)
    for i in range(len(lines)):
        splits = lines[i].split(' ')
        for j in range(len(splits)):
            #print(new_array[i][j])
            new_array[i,j] = final_embeddings[dictionary[str(splits[j])]-1].reshape(32,1)
    

    Now I know we can use list comprehension but for simplicity sake I am using a nested for loop. Hope this helps others who come across this post.

提交回复
热议问题