【问题标题】:Remove a sub list from nested list based on an element in Python基于Python中的元素从嵌套列表中删除子列表
【发布时间】:2015-11-16 10:28:40
【问题描述】:

我有以下列表:

 l = [["a", "done"], ["c", "not done"]]

如果每个子列表的第二个元素是“完成”,我想删除该子列表。 所以输出应该是:

l = [["c", "not done"]]

显然以下不起作用:

for i in range(len(l)):
    if l[i][1] == "done":
        l.pop(0)

【问题讨论】:

    标签: python list nested-lists


    【解决方案1】:

    使用list_comprehension。它只是通过迭代子列表来构建一个新列表,其中每个子列表中的第二个元素不包含字符串done

    >>> l = [["a", "done"], ["c", "not done"]]
    >>> [subl for subl in l if subl[1] != 'done']
    [['c', 'not done']]
    >>> 
    

    【讨论】:

      【解决方案2】:
      l = [["a", "done"], ["c", "not done"]]
      print [i for i in l if i[1]!="done"]
      

      或使用filter

      l = [["a", "done"], ["c", "not done"]]
      print filter(lambda x:x[1]!="done",l)
      

      【讨论】:

        【解决方案3】:

        为您的条件应用过滤器:

        l = [["a", "done"], ["c", "not done"]]
        l = filter(lambda x: len(x)>=2 and x[1]!='done', l)
        

        【讨论】:

          【解决方案4】:

          状态索引为 1,您检查了索引 0

          for i in range(len(l)):
                 if(l[i][1] == "done"):
                     l.pop(i)
          

          【讨论】:

          • 最好在你的回答中加入一点解释
          • 我更正了答案...但是范围内的 for 循环将不起作用,因为您会得到一个超出范围错误的索引
          【解决方案5】:

          使用列表理解:

          l = [ item for item in l if item[-1] != 'done']
          

          【讨论】:

            猜你喜欢
            • 2011-07-14
            • 1970-01-01
            • 2021-07-17
            • 1970-01-01
            • 2023-03-22
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2019-07-13
            相关资源
            最近更新 更多