根据条件从列表中删除项目

时间:2016-03-30 15:24:04

标签: 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)

但由于某种原因,这只删除了一些列表项,但并不是所有列表项都包含第二个条目= m的元组。

5 个答案:

答案 0 :(得分:3)

使用列表理解:

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)

答案 1 :(得分:1)

代码很糟糕,而且我们需要更少 - 这里的内容很少。

[l for l in ls if m not in [i[1] for i in l]]

答案 2 :(得分:0)

在python中过滤列表的最佳方法是使用列表解析:

filtered = [item for item in ls if not(contains_m(item))]

然后您需要的是一个可以判断项目是否包含m的函数,例如:

def contains_m(item):
     return any([tpl[1] == m for tpl in item])

答案 3 :(得分:0)

从迭代中删除itme并不是一个好主意。

试试(如果在这里谈论Python)

ls = [[('a_1', 'a_2'), ('b_1', 'b_2')], [('c_1', 'c_2'), ('d_1', 'd_2'), ('e_1', 'e_2')]]

m='c_2'
print [ x for x in ls if not [ y for y in x if y[1]==m ]]

答案 4 :(得分:0)

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的answer以获得最佳方法。

相关问题