user1827345
user1827345

Reputation: 41

Python: list indices must be integers, not tuple

I'm moving over to Python from Matlab, so I'm only new to Python yet. I'm trying to create a basic piece of code for some data analysis. It should read in all the .txt datafiles in a specified directory and label them with the name of the actual .txt file. I've managed to find a way to get this working using a dictionary, but if there's a better way I'd be very grateful to hear it.

Once I have access to the data I then want to create a new list with manipulated versions of that data. To do this I want to create a new n x m list, or array, however I can't find how to correctly initialise such a list. My latest effort results in the following error:

list indices must be integers, not 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!

Upvotes: 4

Views: 6791

Answers (2)

Abhishek Bhatia
Abhishek Bhatia

Reputation: 716

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

Upvotes: 0

Martijn Pieters
Martijn Pieters

Reputation: 1121962

You are using extended slicing syntax, which only the numpy library supports, on the standard Python list type (your E) variable.

You'll have to use E.append() to add new values to it instead:

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

or simply 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 plain slicing:

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

Upvotes: 3

Related Questions