【问题标题】:How to lowercase of individual word in two dimensional list? [duplicate]如何在二维列表中将单个单词小写? [复制]
【发布时间】:2017-04-15 04:48:38
【问题描述】:

我有二维列表:

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

我想要的输出是:

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

【问题讨论】:

    标签: python python-3.x


    【解决方案1】:

    您可以使用包含另一个列表推导作为其元素的列表推导来做到这一点。这一切的根源是调用str.lower() 来创建新的小写字符串。

    除此之外:最好不要在内置类型之后命名变量。尝试使用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)
    

    【讨论】:

      【解决方案2】:

      你可以试试这个:

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

      【讨论】:

        【解决方案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 方法执行以下操作,这将处理任何深度的字符串嵌套列表

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

        【讨论】:

          猜你喜欢
          • 2019-12-14
          • 2018-04-26
          • 1970-01-01
          • 2019-02-06
          • 2019-12-02
          • 2013-09-29
          • 2021-10-25
          • 2020-01-19
          • 2019-05-05
          相关资源
          最近更新 更多