allankey allankey - 29 days ago 5
Python Question

Python combining information in a list of lists using indexes in a tuple

I have a main data source consisting of a list of lists and a dictionary of tuples that indexes the information I need from the main data source.

I would like to use the dictionary of tuples to index each entry from the main data source and create a new list with this information.

I have created the code below but the the error says "TypeError: list indices must be integers, not generator"

I have searched for how to iterate through each list in a list of lists but have not found the solution.

Any suggestions welcome.

#List of data
MyDat = [['round', 'square', 'oblong', 'circle', 'round'],['orange','orange','purple','green','yellow'], ['rough','rough','smooth','rough','smooth']]

#Tuples required to create new list of variable combinations
tupDict = {"stage1": (0,2), "stage2": (1,)}

newList = []

for i in tupDict:
newList.append(MyDat[(x for x in tupDict[i])])

print(newList)


The new list should create a new list of lists of the columns selected in the MyDat. For example:

Stage1: (0,2)


would create this list

[['round', 'square', 'oblong', 'circle', 'round'], ['rough','rough','smooth','rough','smooth']]

Answer

If I understand correctly you can try like this:

MyDat = [['round', 'square', 'oblong', 'circle', 'round'],['orange','orange','purple','green','yellow'],    ['rough','rough','smooth','rough','smooth']]

#Tuples required to create new list of variable combinations 
tupDict = {"stage1": (0,2), "stage2": (1,)}

newList = []

for i in tupDict:
    newList.extend([MyDat[x] for x in tupDict[i]])

print(newList)

I just changed this line:

newList.append(MyDat[(x for x in tupDict[i])])

To this:

newList.extend([MyDat[x] for x in tupDict[i]])

In this line: newList.append(MyDat[(x for x in tupDict[i])]) you are using a tuple as a index of the MyDat. But integer is needed.