Matrix of files

I would like to create a matrix from files using (for collecting using genfromtxt)

I wrote this small piece of code ... but looks does not works at all

array[0].append(np.genfromtxt('alpha_mean/alpha_75/alphas.000521604.dat',usecols=(0,)))

Where alphas.000521604.dat is 4 columns data number.

During execute this command everything looks works but if I try for example to do:

array=[ [0] for i in range(1)  ]
array[0].append(np.genfromtxt('alpha_mean/alpha_75/alphas.000521604.dat',usecols=(0,)))
array[0][4]

Outputs:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range

and I really don't know why ... can somebody help me out please?

But when we are speak about 3D white:

array=[] 
array.append(genfromtxt'file',usecols=(0,)) t

This works and is not only one index array ...

1 answer

  • answered 2020-09-24 14:56 Ralf

    You can easily see the mistake if you print the intermediate state of the array variable

    >>> array = [[0] for _ in range(1)]
    >>> array
    [[0]]
    # 'array' is a list with one element, which is a list with one element as well,
    # and that single element is the integer 0
    
    >>> array[0]
    [0, ]
    # 'array' is a list with one element, so this shows that that element is
    # a list with also 1 elements
    
    >>> array[0].append('something')
    >>> array
    [[0, 'something']]
    # the nested list has gotten a second element, which for this example is
    # the string 'something'
    
    >>> array[0]
    [0, 'something']
    # 'array' is a list with one element, so this shows that that element is
    # a list with now 2 elements
    
    >>> array[0][4]
    Traceback (most recent call last):
      File "<input>", line 1, in <module>
    IndexError: list index out of range
    # this fails because 'array[0]' is a list with only 2 elements, not 5;
    # 'array[0][4]' tries to access the fifth element (indexing starts at 0)