Python 根据条件从列表中删除项目
我有一个整数元组列表Python 根据条件从列表中删除项目,python,arrays,list,Python,Arrays,List,我有一个整数元组列表 ls = [[(a_1, a_2), (b_1, b_2)], [(c_1, c_2), (d_1, d_2), (e_1, e_2)], ...] 我需要删除包含第二个条目等于预定整数的元组的ls的每一项 我试过这个: for item in ls: for tpl in item: if tpl[1] == m: ls.remove(item) 但出于某些原因,这只删除了少数列表项,而不是所有包含第二个entry=m的元组的列
ls = [[(a_1, a_2), (b_1, b_2)], [(c_1, c_2), (d_1, d_2), (e_1, e_2)], ...]
我需要删除包含第二个条目等于预定整数的元组的ls的每一项
我试过这个:
for item in ls:
for tpl in item:
if tpl[1] == m:
ls.remove(item)
但出于某些原因,这只删除了少数列表项,而不是所有包含第二个entry=m的元组的列表项。在python中过滤列表的最佳方法是使用列表理解:
filtered = [item for item in ls if not(contains_m(item))]
ls = [item for item in ls if all(tuple[1] != m for tuple in item)]
然后,您只需要一个函数就可以判断一个项是否包含m,例如:
def contains_m(item):
return any([tpl[1] == m for tpl in item])
在python中过滤列表的最佳方法是使用列表理解:
filtered = [item for item in ls if not(contains_m(item))]
ls = [item for item in ls if all(tuple[1] != m for tuple in item)]
然后,您只需要一个函数就可以判断一个项是否包含m,例如:
def contains_m(item):
return any([tpl[1] == m for tpl in item])
使用列表理解:
filtered = [item for item in ls if not(contains_m(item))]
ls = [item for item in ls if all(tuple[1] != m for tuple in item)]
或使用过滤器:
ls = filter(lambda item: all(tuple[1] != m for tuple in item),ls)
使用列表理解:
filtered = [item for item in ls if not(contains_m(item))]
ls = [item for item in ls if all(tuple[1] != m for tuple in item)]
或使用过滤器:
ls = filter(lambda item: all(tuple[1] != m for tuple in item),ls)
在遍历列表时,从列表中删除itme不是一个好主意 试试看(如果你在这里说Python的话)
在遍历列表时,从列表中删除itme不是一个好主意 试试看(如果你在这里说Python的话)
Python的列表迭代器是惰性的。这意味着当您从列表中删除一个项目时,它将跳过下一个项目。例如,假设您要从以下列表中删除所有对象:
[1, 1, 2]
您的for
循环从索引0
开始:
[1, 1, 2]
^
它将删除元素并继续:
[1, 2]
^
这个例子只是为了帮助说明这个问题。一个简单的解决方法是使用索引向后循环:
for ind in range(len(ls)-1, -1, -1):
item = ls[ind]
for tpl in item:
if tpl[1] == m:
del ls[ind]
break # You can end the inner loop immediately in this case
另一种方法是复制列表进行迭代,但从原始列表中删除:
for item in ls[:]:
for tpl in item:
if tpl[1] == m:
ls.remove(item)
break
最后一种方法可以简化为创建只包含所需元素的输出列表。这是用列表理解最容易做到的。请参阅@AlexeySmirnov's以获得最佳方法。Python的列表迭代器是懒惰的。这意味着当您从列表中删除一个项目时,它将跳过下一个项目。例如,假设您要从以下列表中删除所有对象:
[1, 1, 2]
您的for
循环从索引0
开始:
[1, 1, 2]
^
它将删除元素并继续:
[1, 2]
^
这个例子只是为了帮助说明这个问题。一个简单的解决方法是使用索引向后循环:
for ind in range(len(ls)-1, -1, -1):
item = ls[ind]
for tpl in item:
if tpl[1] == m:
del ls[ind]
break # You can end the inner loop immediately in this case
另一种方法是复制列表进行迭代,但从原始列表中删除:
for item in ls[:]:
for tpl in item:
if tpl[1] == m:
ls.remove(item)
break
最后一种方法可以简化为创建只包含所需元素的输出列表。这是用列表理解最容易做到的。请参阅@AlexeySmirnov’s,以了解实现这一点的最佳方法。代码很糟糕,我们需要的代码更少——这里是尽可能少的代码
[l for l in ls if m not in [i[1] for i in l]]
代码很烂,我们需要更少的代码——这里的代码非常稀疏
[l for l in ls if m not in [i[1] for i in l]]
您应该使用正在使用的编程语言对此进行标记。看起来ls是元组数组的列表,这意味着您需要第三个循环来遍历数组。看起来ls是元组数组的列表,这意味着您需要第三个循环来遍历数组。将
all
更改为any
和=
到=
如果合适-我永远记不起过滤条件是否只保留或返回那些函数返回'True'的值…将所有
更改为任何
和=
到=
如果合适-我永远记不起过滤条件是否只保留或返回那些函数返回'True'的条件。。。