filtering elements from list of lists in Python?

后端 未结 7 794
鱼传尺愫
鱼传尺愫 2020-12-06 11:29

I want to filter elements from a list of lists, and iterate over the elements of each element using a lambda. For example, given the list:

a = [[1,2,3],[4,5         


        
7条回答
  •  猫巷女王i
    2020-12-06 11:34

    You can explicitly name the sublist elements (assuming there's always a fixed number of them), by giving lambda a tuple as its argument:

    >>> a = [[1,2,3],[4,5,6]]
    >>> N = 10
    >>> filter(lambda (i, j, k): i + j + k > N, a)
    [[4, 5, 6]]
    

    If you specify "lambda i, j, k" as you tried to do, you're saying lambda will receive three arguments. But filter will give lambda each element of a, that is, one sublist at a time (thus the error you got). By enclosing the arguments to lambda in parenthesis, you're saying that lambda will receive one argument, but you're also naming each of its components.

提交回复
热议问题