filtering elements from list of lists in Python?

后端 未结 7 775
鱼传尺愫
鱼传尺愫 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条回答
  • 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.

    0 讨论(0)
  • 2020-12-06 11:34

    Use a function instead of a lambda, then myVar = a[0], etc.

    0 讨论(0)
  • 2020-12-06 11:38

    How about this?

    filter(lambda b : reduce(lambda x, y : x + y, b) >= N, a)

    This isn't answering the question asked, I know, but it works for arbitrarily-long lists, and arbitrarily-long sublists, and supports any operation that works under reduce().

    0 讨论(0)
  • 2020-12-06 11:45

    Ok, obviously you know that you can use sum. The goal of what you are trying to do seems a bit vague, but I think that the optional parameter syntax might help you out, or at least give you some inspiration. If you place a * before a parameter, it creates a tuple of all of itself and all of the remaining parameters. If you place a ** before it, you get a dictionary.

    To see this:

    def print_test(a,b,c,*d):
        print a
        print b
        print c
        print d
    
    print_test(1,2,3,4,5,6)
    

    prints

    1
    2
    3
    (4, 5, 6)
    

    You can use this syntax with lambda too.

    Like I said, I'm not sure exactly what you are trying to do, but it sounds like this might help. I don't think you can get local variable assignments in lambda without some hacking, but maybe you can use this to assign the values to variables somehow.

    Edit: Ah, I understand what you are looking for moreso now. I think you want:

    lambda (a, b, c): a+b+c > N
    
    0 讨论(0)
  • 2020-12-06 11:53

    You can do something like

    >>> a=[[1,2,3],[4,5,6]]
    >>> filter(lambda (x,y,z),: x+y+z>6, a)
    [[4, 5, 6]]
    

    Using the deconstruction syntax.

    0 讨论(0)
  • 2020-12-06 11:55

    Try something like this:

    filter(lambda a: a[0] + a[1] + a[2] >= N, a)
    
    0 讨论(0)
提交回复
热议问题