Search code examples
pythonpython-2.7listcomparisonsublist

How to add a sublist to a sublist?


I want to append a sublist to the previous sublist under certain circumstances, i.e. if its length is less than 2. So, the length of [5] less than 2 and now the previous list is to be extended with the 5 (a+b).

a = [1,1,1,1]
b = [5]
c = [1,1,1]
d = [1,1,1,1,1]
e = [1,2]
f = [1,1,1,1,1,1]

L = [a,b,c,d,e,f]

print 'List:', L

def short(lists):
    result = []
    for value in lists:
        if len(value) <= 2 and result:
            result[-1] = result[-1] + value
    return result

result = short(L)
print 'Result:', result

The result should be: [[1, 1, 1, 1, 5], [1, 1, 1], [1, 1, 1, 1, 1, 2], [1, 1, 1, 1, 1, 1]]

But from my code, I get: []


Solution

  • This might help

    Ex:

    a = [1,1,1,1]
    b = [5]
    c = [1,1,1]
    d = [1,1,1,1,1]
    e = [1,2]
    f = [1,1,1,1,1,1]
    
    L = [a,b,c,d,e,f]
    
    print( 'List:', L)
    
    def short(lists):
        result = []
        for value in lists:
            if len(value) <= 2:            #check len
                result[-1].extend(value)   #extend to previous list
            else:
                result.append(value)       #append list. 
        return result
    
    result = short(L)
    print( 'Result:', result)
    

    Output:

    List: [[1, 1, 1, 1], [5], [1, 1, 1], [1, 1, 1, 1, 1], [1, 2], [1, 1, 1, 1, 1, 1]]
    Result: [[1, 1, 1, 1, 5], [1, 1, 1], [1, 1, 1, 1, 1, 1, 2], [1, 1, 1, 1, 1, 1]]