采用嵌套字符串列表并返回一个新的嵌套列表并且所有字符串都大写的函数?

6 python function capitalize

这将使它们大写,但仅限于没有嵌套列表.

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

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

print capitalize_nested(t)
Run Code Online (Sandbox Code Playgroud)

我无法弄清楚如何打印出一个嵌套列表,其中所有字符串都以大写字母开头.我一定错过了一些明显的东西,这让我很难过.

Dav*_*son 11

使用递归解决方案(使用列表推导也有助于使其更紧凑):

def capitalize_nested(t):
    if isinstance(t, list):
        return [capitalize_nested(s) for s in t]
    else:
        return t.capitalize()
Run Code Online (Sandbox Code Playgroud)

例如:

print capitalize_nested(['this', 'that', ['other']])
# ['This', 'That', ['Other']]
Run Code Online (Sandbox Code Playgroud)