如何将二维列表中的单个单词小写?

2024-03-29 15:16:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个二维列表:

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

我想要的输出是:

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

Tags: hello列表newworldyourmylistours
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)

你可以试试这个:

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']]

嵌套列表理解将为您的情况

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"]

相关问题 更多 >