Creating variable number of variables in python

前端 未结 2 1957
陌清茗
陌清茗 2021-01-29 10:45

I am trying to create a variable number of variables (arrays) in python.

I have a database from experiments and I am extracting data from it. I do not have control over

2条回答
  •  清酒与你
    2021-01-29 11:44

    I didn't understand much from your explanation of the problem, but from what you wrote it sounds like a normal list would do the job:

    arr1 = []
    
    if (your condition here):
        arr1.append(A[i][0])
    

    memory management is dynamic, i.e. it allocates new memory as needed and afterwards if you need a numpy array just make numpy_array = np.asarray(arr1).

    A (very) small primer on lists in python:

    A list in python is a mutable container that stores references to objects of any kind. Unlike C++, in a python list your items can be anything and you don't have to specify the list size when you define it. In the example above, arr1 is initially defined as empty and every time you call arr1.append() a new reference to A[i][0] is pushed at the end of the list.

    For example:

    a = []
    a.append(1)
    a.append('a string')
    b = {'dict_key':'my value'}
    a.append(b)
    print(a)
    

    displays:

    [1, 'a string', {'dict_key': 'my value'}]
    

    As you can see, the list doesn't really care what you append, it will store a reference to the item and increase its size of 1.

    I strongly suggest you to take a look at the daa structures documentation for further insight on how lists work and some of their caveats.

提交回复
热议问题