根据 Python 中的元素从嵌套列表中删除子列表
Remove a sub list from nested list based on an element in Python
我有以下列表:
l = [["a", "done"], ["c", "not done"]]
如果每个子列表的第二个元素是 "done" 我想删除该子列表。
所以输出应该是:
l = [["c", "not done"]]
显然下面的方法不起作用:
for i in range(len(l)):
if l[i][1] == "done":
l.pop(0)
使用list_comprehension
。它只是通过迭代子列表来构建一个新列表,其中每个子列表中的第二个元素将不包含字符串 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"]
或使用filter
l = [["a", "done"], ["c", "not done"]]
print filter(lambda x:x[1]!="done",l)
根据您的条件应用过滤器:
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 = [ item for item in l if item[-1] != 'done']
我有以下列表:
l = [["a", "done"], ["c", "not done"]]
如果每个子列表的第二个元素是 "done" 我想删除该子列表。 所以输出应该是:
l = [["c", "not done"]]
显然下面的方法不起作用:
for i in range(len(l)):
if l[i][1] == "done":
l.pop(0)
使用list_comprehension
。它只是通过迭代子列表来构建一个新列表,其中每个子列表中的第二个元素将不包含字符串 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"]
或使用filter
l = [["a", "done"], ["c", "not done"]]
print filter(lambda x:x[1]!="done",l)
根据您的条件应用过滤器:
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 = [ item for item in l if item[-1] != 'done']