Organizing a random list of objects in Python.

Posted by Saebin on Stack Overflow See other posts from Stack Overflow or by Saebin
Published on 2010-05-13T17:16:27Z Indexed on 2010/05/13 19:44 UTC
Read the original article Hit count: 218

Filed under:
|
|

So I have a list that I want to convert to a list that contains a list for each group of objects.

ie ['objA.attr1', 'objC', 'objA.attr55', 'objB.attr4'] would return [['objA.attr1', 'objA.attr55'], ['objC'], ['objB.attr4']]

currently this is what I use:

givenList = ['a.attr1', 'b', 'a.attr55', 'c.attr4']
trgList = []
objNames = []
for val in givenList:
    obj = val.split('.')[0]
    if obj in objNames:
        id = objNames.index(obj)
        trgList[id].append(val)
    else:
        objNames.append(obj)
        trgList.append([val])
#print trgList

It seems to run a decent speed when the original list has around 100,000 ids... but I am curious if there is a better way to do this. Order of the objects or attributes does not matter. Any ideas?

© Stack Overflow or respective owner

Organizing a random list of objects in Python.

Posted by Saebin on Super User See other posts from Super User or by Saebin
Published on 2010-05-13T17:16:27Z Indexed on 2010/05/13 17:25 UTC
Read the original article Hit count: 218

Filed under:
|
|

So I have a list that I want to convert to a list that contains a list for each group of objects.

ie ['objA.attr1', 'objC', 'objA.attr55', 'objB.attr4'] would return [['objA.attr1', 'objA.attr55'], ['objC'], ['objB.attr4']]

currently this is what I use:

givenList = ['a.attr1', 'b', 'a.attr55', 'c.attr4']
trgList = []
objNames = []
for val in givenList:
    obj = val.split('.')[0]
    if obj in objNames:
        id = objNames.index(obj)
        trgList[id].append(val)
    else:
        objNames.append(obj)
        trgList.append([val])
#print trgList

It seems to run a decent speed when the original list has around 100,000 ids... but I am curious if there is a better way to do this. Order of the objects or attributes does not matter. Any ideas?

© Super User or respective owner

Related posts about python

Related posts about grouping