你可以用
for loops
或
list comprehension
在你的例子中实现这个结果。
all_lists = [['list one'],['list two'],['list...'],['list n']]
作为一个函数,我们可以执行
upper
对于列表中的每个元素,使用
for loop
.
def upper_list(data):
result = []
for nested in data:
changes = []
for element in nested:
changes.append(element.upper())
result.append(changes)
return result
upper_list(all_lists)
#[['LIST ONE'], ['LIST TWO'], ['LIST...'], ['LIST N']]
此外,您可以使用列表理解将上述内容压缩成一行代码。
all_lists = [[element.upper() for element in nested] for nested in all_lists]
这两种方法都适用于包含多个元素的嵌套列表,例如;
all_lists = [['list one', 'test'],['list two','two'],['list...'],['list n']]
>>>[[element.upper() for element in nested] for nested in all_lists]
#[['LIST ONE', 'TEST'], ['LIST TWO', 'TWO'], ['LIST...'], ['LIST N']]