Featured post

new redirect for blender.org bpy docs.

http://www.blender.org/api/blender_python_api_current/ As of 10/11 november 2015 we can now link to the current api docs and not be worr...

May 16, 2011

Blender 2.5 Python Sorting Through A List

Sometimes it's worth a few moments to sort a list procedurally.. there is probably a more pythonic way of sorting it. Here's what works for me, this list happens to be sorted. if it wasn't we'd do a sorted() on it, sorting by the value in the first index of each member list.

'''
if we want a histogram type list like this
[[0, 34, 345], [0, 36, 345]]
[[1, 34, 345], [1, 36, 345], [1, 37, 345]]
[[2, 34, 345]]
[[4, 34, 345], [4, 34, 345]]
[[7, 34, 345]]

from a list like this:
[[0,34,345],[0,36,345],[1,34,345],[1,36,345],[1,37,345],
[2,34,345],[4,34,345],[4,34,345],[7,34,345]]
we can write:
'''

jax = [[0,34,345],[0,36,345],[1,34,345],[1,36,345],[1,37,345],
[2,34,345],[4,34,345],[4,34,345],[7,34,345]]

multi_list = []
temp_list = []
# or multi_list, temp_list = [],[]

# get first track num, this is a one off necessity
tracknum = jax[0][0]

# start digging through the data
for i in range(len(jax)):
    tracknum_line = jax[i][0]
    if not tracknum_line == tracknum:

        #we aren't adding more items for this track
        multi_list.append(temp_list) 
        temp_list = [] # empty the storage list
        
    temp_list.append(jax[i])
    tracknum = tracknum_line

    # if last line, then add templist to multilist
    # we aren't adding more items for this track
    if i == len(jax)-1:
        multi_list.append(temp_list) 
        
for track in multi_list:
    print(track)