[英]Function that takes a nested list of strings and returns a new nested list with all strings capitalized?
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.我一定遗漏了一些明显的东西,这让我很难过。
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']]
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:只需检查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)
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()
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()
L = ['this', 'that', ['other'], ['may',['be', ['nested'], 'further']]]
capitalize_inplace(L)
print(L)
# -> ['This', 'That', ['Other'], ['May', ['Be', ['Nested'], 'Further']]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.