6

这会将它们大写,但前提是没有嵌套列表。

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

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

print capitalize_nested(t)

我不知道如何让它打印出一个嵌套列表,其中所有字符串都以大写字母开头。我一定遗漏了一些明显的东西,这让我很难过。

4

5 回答 5

12

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

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']]
于 2012-12-24T17:57:45.280 回答
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])
于 2012-12-24T17:58:53.950 回答
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)
于 2012-12-24T17:58:52.130 回答
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()
于 2012-12-24T18:30:13.167 回答
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']]]
于 2012-12-24T18:31:46.143 回答