Search code examples
pythonlistpython-2.7expandable

Expanding list of lists


I am looking for a way to optimize the current code that I have:

        for result in results:
            if result != '':
                if isinstance(result, list):
                    for subresult in result:
                        if subresult != '':
                            worksheet.write(r, c, subresult)
                            c += 1
                else:
                    worksheet.write(r, c, result)
                    c += 1

I also use this in a particular case:

        for result in results:
            if isinstance(result, list):
                for subresult in result:
                    worksheet.write(r, c, subresult)
                    c += 1
            else:
                worksheet.write(r, c, result)
                c += 1

I have a list that in some instances contains only a single value, while in other instances it contains multiple values (i.e. another list).

Here is an example of what the list may contain:

results = ['', '', '', '390', '66', ['Name', 'SerialNumber', 'Model', 'Year'], 'SW_Version', ['HD_Loc', 'HD_Model', 'HD_FW', 'HD_SerialNumber', 'Man_Yr', 'Man_Mth'], '', '', '']

Ultimately I want to be able to output each value to its own column in excel. In some cases I only want to output the parts of the list that contain a value, which is performed by the first snippet of code I provided. In other cases I want to output all parts of the list, regardless of whether it has a value or not, which is performed by the second snippet of code I provided.

I have seen instances where a for loop and some action statement, lets say print, have been combined into a single line of python code, but I have been unable to get that syntax to work with the snippets that I have provided.

This code is currently working in the way I have implemented it, I am just looking for a way to shorten/optimize it as the program I have it inside of is starting to get fairly large and being able to shorten this would help me in shortening other parts of the program also.

Thanks in advance!

Edit: In both cases the order of which it is output does matter, and I would like to have it output in the order that it is currently in (just minus the '' in the one scenario).


Solution

  • I hope this helps,

    results = ['', '', '', '390', '66', ['Name', 'SerialNumber', 'Model', 'Year'], 'SW_Version', ['HD_Loc', 'HD_Model', 'HD_FW', 'HD_SerialNumber', 'Man_Yr', 'Man_Mth'], '', '', '']
    
    flatList = [item for sublist in [[item] if not isinstance(item,list) else item for item in results] for item in sublist]
    
    flatListWithoutBlanks = [item for item in [item for sublist in [[item] if not isinstance(item,list) else item for item in results] for item in sublist] if item != '' ]
    

    best,