如果满足lambda条件,则删除整个列表

时间:2017-05-16 19:44:00

标签: python lambda

假设您有一个列表列表:

[[1,2,3,4,5,6],[2,3,4,5,6,7],['a',12,3,4,5,], ['a',123,4,5,6]]

我可以删除(使用lambda)第一个元素中包含a的列表吗? 我开始玩Python的lambda,这已经让我困惑了一段时间。可以吗?

3 个答案:

答案 0 :(得分:5)

filter从给定列表中删除给定函数返回False的元素。列表推导可以与谓词类似地使用。

>>> xss = [[1,2,3,4,5,6],[2,3,4,5,6,7],['a',12,3,4,5,], ['a',123,4,5,6]]
>>> list(filter(lambda xs: len(xs) != 0 and xs[0] != 'a', xss))
[[1, 2, 3, 4, 5, 6], [2, 3, 4, 5, 6, 7]]
>>> [xs for xs in xss if len(xs) != 0 and xs[0] != 'a']
[[1, 2, 3, 4, 5, 6], [2, 3, 4, 5, 6, 7]]

答案 1 :(得分:0)

@rightfold是对的,不过如果你想让它成为一个带有' a'的列表的通用名称。在任何位置:

>>>test_list = [[1, 2, 3, 4, 5, 6], [2, 3, 4, 5, 6, 7], ['a', 12, 3, 4, 5], ['a', 123, 4, 5, 6]]
>>>filter(lambda x: len(x) > 0 and 'a' not in x, test_list)
[[1, 2, 3, 4, 5, 6], [2, 3, 4, 5, 6, 7]]
>>>[x for x in test_list if len(x) > 0 and 'a' not in x]
[[1, 2, 3, 4, 5, 6], [2, 3, 4, 5, 6, 7]]

答案 2 :(得分:0)

filter(lambda i: i if i[0] != 'a' else False, [[1,2,3,4,5,6],[2,3,4,5,6,7],['a',12,3,4,5,], ['a',123,4,5,6]])