Function that takes a nested list of strings and returns a new nested list with all strings capitalized?

StackOverflow https://stackoverflow.com/questions/14024325

  •  12-12-2021
  •  | 
  •  

Question

This will capitalize them but only if there are no nested lists.

t = ['this','that', ['other']]

def capitalize_nested(t):
    res = []
    for s in t:
        res.append(s.capitalize())
    return res

print capitalize_nested(t)

I can't figure out how to get it to print out a nested list having all of the strings start with a capital letter. I must be missing something obvious, this just has me stumped.

Was it helpful?

Solution

Use a recursive solution (and using list comprehensions also helps make it more compact):

def capitalize_nested(t):
    if isinstance(t, list):
        return [capitalize_nested(s) for s in t]
    else:
        return t.capitalize()

For example:

print capitalize_nested(['this', 'that', ['other']])
# ['This', 'That', ['Other']]

OTHER TIPS

def cap(L):
    for i,elem in enumerate(L):
         if isinstance(elem, str):
             L[i] = elem.capitalize()
         elif isinstance(elem, list):
             cap(L[i])

Just check if s is a list then recursively call your capitalize_nested function:

t = ['this','that', ['other']]

def capitalize_nested(t):
    res = []
    for s in t:
        if type(s) == list:
            res.append(capitalize_nested(s))
        else:
            res.append(s.capitalize())
    return res

print capitalize_nested(t)

Here's a version that supports an arbitrary deep nested list:

from collections import MutableSequence

def capitalize_inplace(nested_list):
    stack = [nested_list]
    while stack:
        lst = stack.pop()
        for i, item in enumerate(lst):
            if isinstance(item, MutableSequence):
                stack.append(item)
            else:
                lst[i] = item.capitalize()

Example

L = ['this', 'that', ['other'], ['may',['be', ['nested'], 'further']]]
capitalize_inplace(L)
print(L)
# -> ['This', 'That', ['Other'], ['May', ['Be', ['Nested'], 'Further']]]

The recursive solution is first solution and most beautiful solution, but not always the best solution, Check this iterative solution too:

def capitalize(t):
    lists = [t]
    while lists:
        l = lists.pop()
        for i, item in enumerate(l):
            if isinstance(item, list):
                lists.append(item)
            else:
                l[i] = item.capitalize()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top