Search code examples
pythonmultidimensional-arraypython-2.5

Python_grouping multidimensional list


I have an example multidimensional list:

    example_list=[
        ["a","b","c", 2,4,5,7],
        ["e","f","g",0,0,1,5],
        ["e","f","g", 1,4,5,7],
        ["a","b","c", 3,2,5,7]
    ]

How is it possible to put them in groups like this:

out_list=[
         [["a","b","c", 2,4,5,7],
           ["a","b","c",3,2,5,7]
         ],
         [["e","f","g", 0,0,1,5],
          ["e","f","g", 1,4,5,7]
         ]
 ]

I have tried this:

example_list=[["a","b","c", 2,4,5,7],["e","f","g", 0,0,1,5],["e","f","g",1,4,5,7],["a","b","c", 3,2,5,7]]
unique=[]
index=0
for i in range(len(example_list)):
    newlist=[]
    if example_list[i][:3]==example_list[index][:3]:
        newlist.append(example_list[i])
    index=index+1
    unique.append(newlist)            
print unique

My results is this:

[[['a', 'b', 'c', 2, 4, 5, 7]], [['e', 'f', 'g',0, 0, 1, 5]], [['e', 'f', 'g', 1, 4, 5, 7]], [['a', 'b', 'c', 3, 2, 5,7]]]

I could not figure it out.


Solution

  • If the grouping is decided by the first three elements in each list following code will do what you're asking for:

    from collections import defaultdict
    
    example_list=[["a","b","c", 2,4,5,7],["e","f","g",0,0,1,5],["e","f","g", 1,4,5,7],["a","b","c", 3,2,5,7]]
    d = defaultdict(list)
    for l in example_list:
        d[tuple(l[:3])].append(l)
    
    print d.values() # [[['a', 'b', 'c', 2, 4, 5, 7], ['a', 'b', 'c', 3, 2, 5, 7]], ...]
    

    This will use defaultdict to generate a dictionary where keys are the first three elements and values are list of lists which start with those elements.