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

时间:2012-12-24 17:54:28

标签: 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)

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

5 个答案:

答案 0 :(得分:11)

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

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

例如:

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

答案 1 :(得分:3)

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

答案 2 :(得分:2)

只需检查s是否为列表,然后以递归方式调用capitalize_nested函数:

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)

答案 3 :(得分:1)

递归解决方案是第一个解决方案和最美观的解决方案,但并不总是最佳解决方案,请检查此迭代解决方案:

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()

答案 4 :(得分:1)

这是一个支持任意深层嵌套列表的版本:

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()

实施例

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