2016-11-30 21 views

回答

3

你可以用它包含一个列表理解这样做,因为它的元素,另一个列表理解。在这一切的根源是str.lower()调用创建新casified低弦。

旁白:这是最好不要命名变量内置后的类型。尝试my_list=lst=,或一些描述性的名称,如mixed_case_words=,而不是list=

new_list = [ [ item.lower() for item in sublist ] for sublist in old_list] 

如果你喜欢的循环,你可以用嵌套for循环做到这一点:

new_list = [] 
for sublist in old_list: 
    new_sublist = [] 
    for item in sublist: 
     new_sublist.append(item.lower()) 
    new_list.append(new_sublist) 
1

你可以试试这个:

list=[["Hello", "mY", "WORLD"], ["MY", "yOur", "ouRS"]] 
new_list = [ [ i.lower() for i in innerlist ] for innerlist in list] 
print(new_list) 

输出:

[['hello', 'my', 'world'], ['my', 'your', 'ours']] 
0

嵌套列表理解会为你的情况做

lst = [["Hello", "mY", "WORLD"], ["MY", "yOur", "ouRS"]] 
new_lst = [ [i.lower() for i in j] for j in lst] 
# [["hello", "my", "world"], ["my", "your", "ours"] 

我们可以做类似下面也采用evalstr方法,这要处理字符串的嵌套列表中的任何深度

lst = [["Hello", "mY", "WORLD"], ["MY", "yOur", "ouRS"]] 
# replace eval with ast.literal_eval for safer eval 
new_lst = eval(str(lst).lower()) 
# [["hello", "my", "world"], ["my", "your", "ours"] 
相关问题