Quester
Quester

Reputation: 2009

A program to mutate Nested Lists

Could someone help me do two things:

  1. Review the code and see if it could be written in a better way.
  2. Finish this program. I got stuck in trying to put the list back the way it is. i.e. a nested list of lists.

Here we go:

t = ['a', 'b', ['c', 'd'], ['e'], 'f']

def capitalize_list(t):
    L = []
    N = []
    for i in range(len(t)):
        if type(t[i]) == str:
            L.append(t[i].capitalize())
        if type(t[i]) == list:
            L.extend(t[i])
            for s in L:
                N.append(s.capitalize())
     print N 

 capitalize_list(t)

This code prints:

['A', 'B', 'C', 'D', 'E', 'F']

I need it to print:

['A', 'B', ['C', 'D'], ['E'], 'F']

Upvotes: 2

Views: 720

Answers (2)

Stuart
Stuart

Reputation: 9868

An alternative way of doing this recursively:

def capitalize(item):
    if type(item) is str:
        return item.capitalize()
    if type(item) is list:
        return map(capitalize, item)

You could even do

def capitalize(item):
    try:
        return item.capitalize()
    except AttributeError:
        return map(capitalize, item)

-- which would use the capitalize method for any object that has it (such as a normal or unicode string) and attempt to iterate through any object that does not.

Upvotes: 1

perreal
perreal

Reputation: 98118

You can use recursion:

def capitalize_list(t):
    N = []
    for i in range(len(t)):
        if type(t[i]) == str:
            N.append(t[i].capitalize())
        if type(t[i]) == list:
            N.append(capitalize_list(t[i]))
    return N

Output:

['A', 'B', ['C', 'D'], ['E'], 'F']

Upvotes: 3

Related Questions