假设您有一个列表列表:
[[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,这已经让我困惑了一段时间。可以吗?
答案 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]])