pythonindexingnested-lists

Creating nested lists from a single list


Suppose I have a list like this:

my_list = ['a_norm', 'a_std', 'a_min', 'a_max', 'a_flag', 'b_norm', 'b_std', 'b_min', 'b_max', 'b_flag', 'c_norm', 'c_std', 'c_min', 'c_max', 'c_flag']

I want to parse this list and create nested lists within separate lists like this. It is very important that I retain the order of the :

a_list = [[1, "a_norm"], [2, "a_std"], [3, "a_min"], [4, "a_max"], [5, "a_flag"]]
b_list = [[1, "b_norm"], [2, "b_std"], [3, "b_min"], [4, "b_max"], [5, "b_flag"]]
c_list = [[1, "c_norm"], [2, "c_std"], [3, "c_min"], [4, "c_max"], [5, "c_flag"]]

I tried the below which, in addition to being convoluted, did not work (endless loop). Any suggestions on how to accomplish my end goal?

a_list = []
b_list = []
c_list = []
i = 1
j = 1
k = 1
while (i < 6) and (j < 6) and (k < 6):
    for item in my_list:
        if 'a' in item:
            a_list.append(i)
            a_list.append(item)
            i + 1
        elif 'b' in my_list:
            b_list.append(j)
            b_list.append(item)
            j + 1
        elif 'c' in my_list:
            c_list.append(k)
            c_list.append(item)
            k + 1

Solution

  • This will do the parsing you want; you can then assign the items in parsed_lists as you wish.

    parsed_lists = {'a':[], 'b':[], 'c':[]}
    for x in my_list:
        v = parsed_lists[x[0]]
        v.append([len(v)+1,x])
    

    which results in:

    {'a': [[1, 'a_norm'], [2, 'a_std'], [3, 'a_min'], [4, 'a_max'], [5, 'a_flag']], 
     'b': [[1, 'b_norm'], [2, 'b_std'], [3, 'b_min'], [4, 'b_max'], [5, 'b_flag']], 
     'c': [[1, 'c_norm'], [2, 'c_std'], [3, 'c_min'], [4, 'c_max'], [5, 'c_flag']]}