简体   繁体   中英

Remove a sub list from nested list based on an element in Python

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)

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

>>> l = [["a", "done"], ["c", "not done"]]
>>> [subl for subl in l if subl[1] != 'done']
[['c', 'not done']]
>>> 
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)

Apply a filter for your criteria:

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

status index is 1, you checked index 0

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

用这个:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM