views:

38

answers:

1

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?

A: 

This needs to be better defined: what do you do when there is no property? What order do you want the final list as? What about duplicates?

A general algorithm would be to use a multi-map: a map that has multiple values per key. You will then scan through the original list, separate each element into an "object" and "property", and then add a key-value pair for the object and property. At the end of this cycle, you will have a mapping from objects to set of properties. You can then iterate over this to build your final list.

You can use a third-party multimap or implement yourself by mapping into a sequence.

You might want to create a dummy property for cases when the object does not have a property.

Uri
Duplicates would not happen and order of the groups and their properties does not matter. If no property is given with an object, a group would need still created, it just wouldn't contain properties (yet).The biggest limitation I didn't mention is the original object.property string must be preserved... otherwise I will have to rebuild the object.property string when I go to pass it to other functions. So although I could use something like a dictionary to store the results, ie d[object1=['attr1','attr2']], ultimately I need the object and property put back together for each property.
Saebin