Python:根据元素从嵌套列表中删除子列表

时间:2022-11-18 19:00:29

I have the following list:

我有以下列表:

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

If the second element of each sub list is "done" I want to remove that the sub list. So the output should be:

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

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

Obviously the below doesn't work:

显然以下不起作用:

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

Any help would be appreciated!!

任何帮助,将不胜感激!!

5 个解决方案

#1


6  

Use list_comprehension. It just builts a new list by iterating over the sublists where the second element in each sublist won't contain the string done

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

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

#2


1  

l = [["a", "done"], ["c", "not done"]]
print [i for i in l if i[1]!="done"]

or use filter

或使用过滤器

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

#3


0  

Apply a filter for your criteria:

根据您的条件应用过滤器:

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

#4


0  

Use this:

用这个:

l = filter(lambda s: s[-1] == 'not done', l)

#5


0  

status index is 1, you checked index 0

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

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

#1


6  

Use list_comprehension. It just builts a new list by iterating over the sublists where the second element in each sublist won't contain the string done

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

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

#2


1  

l = [["a", "done"], ["c", "not done"]]
print [i for i in l if i[1]!="done"]

or use filter

或使用过滤器

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

#3


0  

Apply a filter for your criteria:

根据您的条件应用过滤器:

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

#4


0  

Use this:

用这个:

l = filter(lambda s: s[-1] == 'not done', l)

#5


0  

status index is 1, you checked index 0

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

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