Python: list indices must be integers, not a tuple

I am transitioning to Python from Matlab, so I am new to Python. I am trying to create a basic code snippet for some data analysis. It should read all .txt datafiles in the specified directory and label them with the name of the actual .txt file. I managed to find a way to make this work with a dictionary, but if there is a better way, I would really appreciate it.

As soon as I have access to the data, I want to create a new list with managed versions of this data. To do this, I want to create a new nxm list or an array, however I cannot find how to properly initialize such a list. My last effort results in the following error:

Index indices

must be intact, not a tuple

The code is as follows:

import sys import os import re import string from numpy import * listing = os.listdir(path) dic = {} # define a dictionary to map the datafiles to while maintaining their filename for filename in listing: match = re.findall(r'[\w.]+\.txt', filename) # Use a regular expression findall function to identify all .txt files if match: dic[match.pop()[:-4]] = loadtxt(filename) # Drop the .txt and assign the datafile its original name E = [] E[:,0] = dic['Test_Efield_100GHz'][:,0] E[:,1] = dic['Test_Efield_100GHz'][:,1] E[:,2] = abs(dic['Test_Efield_100GHz'][:,4]+dic['Test_Efield_100GHz'][:,7]*1j)**2 E[:,3] = abs(dic['Test_Efield_100GHz'][:,5]+dic['Test_Efield_100GHz'][:,8]*1j)**2 E[:,4] = abs(dic['Test_Efield_100GHz'][:,6]+dic['Test_Efield_100GHz'][:,9]*1j)**2 

Thanks for any feedback!

+4
source share
2 answers

You use the extended slice syntax, which only the numpy library supports, in the standard Python list variable (your E ).

You will need to use E.append() to add new values ​​to it:

 E.append(dic['Test_Efield_100GHz'][:,0]) 

or just define the whole list as a set of expressions:

 E = [ dic['Test_Efield_100GHz'][:,0] dic['Test_Efield_100GHz'][:,1] abs(dic['Test_Efield_100GHz'][:,4]+dic['Test_Efield_100GHz'][:,7]*1j)**2 abs(dic['Test_Efield_100GHz'][:,5]+dic['Test_Efield_100GHz'][:,8]*1j)**2 abs(dic['Test_Efield_100GHz'][:,6]+dic['Test_Efield_100GHz'][:,9]*1j)**2 ] 

or use a numpy array instead.

Standard python sequence types such as str , list and tuple only support simple indexing:

 E[0] E[-2] 

or simple slicing:

 E[:10] E[1:2] E[3:] E[:-1] 
+3
source

you can specify only one index per array.
Use something like this
E.append(dic['Test_Efield_100GHz'][0])
This will save E [0] as an array, whose values ​​can be accessed via s over E [0] [i], where i is the column name
Note. Python does not have a matrix type data structure, it only has arrays. A matrix is ​​just an array of arrays.

0
source

Source: https://habr.com/ru/post/1446292/


All Articles