1

I'm trying to assign classes to a list of nodes, and separate all nodes into separate lists based on class tag. For example, if we have the following code:

#define number of classes
MaxC=5
index=[4 4 5 1 4 1 4 5 4 4 3 1 3 3 1 1]
def indices(index,func):
    return[v for (v,val) in enumerate(index) if func(val)]

##Create node classes
nodeclass=[[],[],[],[],[],[],[],[],[],[]]
for k in range(0,MaxC):
    nodeindex=indices(index, lambda p:p==k)
    nodeclass[k].append([nodeindex])

Then we will get a list of lists corresponding to the node index locations for each class:

[[[[]]] [[[3, 5, 11, 14, 15]]] [[[]]] [[[10, 12, 13]]]
 [[[0, 1, 4, 6, 8, 9]]] [] [] [] [] []]

However, this result produces lists on lists on lists on lists. This becomes a problem later in my script when I want to iterate over the node index locations, but am getting returned errors because the iterator is receiving a list, rather than the individual elements.

TL;DR: Is there a way I can more efficiently generate these index locations so that I do not receive a list of lists? In the worst case scenario, if this is not possible, how to flatten the list to a form of:

[[],[3,5,11,14,15],[],[10,12,13],[0,1,4,6,8,9],[],[],[],[]]
Brandon Ginley
  • 249
  • 3
  • 12
  • Could this be of help ? http://stackoverflow.com/questions/406121/flattening-a-shallow-list-in-python or this : http://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-python – Andy M Jun 23 '15 at 14:50
  • What is this? `index=[4. 4. 5. 1. 4. 1. 4. 5. 4. 4. 3. 1. 3. 3. 1. 1.]` ? This isn't proper Python. – Reut Sharabani Jun 23 '15 at 14:55
  • @ReutSharabani Fixed. I copied the readout from my iPython terminal, and forgot to erase the periods. – Brandon Ginley Jun 23 '15 at 15:18

1 Answers1

3

Change your last line to:

nodeclass[k].extend(nodeindex)

The two extra list wrappings you're creating are happening in:

  1. The list comprehension inside the indices function.
  2. The [nodeindex] wrap in the append call.
sykora
  • 96,888
  • 11
  • 64
  • 71
  • Thank you. I had tried using extend earlier, but was returned an error. I don't know why I couldn't figure it out before, but now it is running with no errors. Thanks a bunch! – Brandon Ginley Jun 23 '15 at 15:20