关于python:如何在二维列表中使用单个单词的小写字母?

How to lowercase of individual word in two dimensional list?

本问题已经有最佳答案,请猛点这里访问。

我有二维列表:

1
list=[["Hello","mY","WORLD"], ["MY","yOur","ouRS"]]

我想要的输出是:

1
new_list=[["hello","my","world"], ["my","your","ours"]]

您可以使用一个包含另一个列表理解(作为其元素)的列表理解来完成此操作。它的根目录是对str.lower()的调用,以创建新的较低的casified字符串。

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

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

如果您喜欢循环,可以使用嵌套的for循环:

1
2
3
4
5
6
new_list = []
for sublist in old_list:
    new_sublist = []
    for item in sublist:
        new_sublist.append(item.lower())
    new_list.append(new_sublist)

您可以尝试以下操作:

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

输出:

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


嵌套列表理解将对您的案例起作用

1
2
3
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方法,这样可以处理字符串嵌套列表的任何深度。

1
2
3
4
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"]