How to get filter to work with a lambda taking multiple arguments?

后端 未结 9 1062
闹比i
闹比i 2020-12-08 22:11

Using Python, am finding it difficult to get filter() to work with lambda for cases where more than 1 argument needs to be passed as is the case in the following snippet:

9条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-08 22:57

    This would work for sequences of any length:

    all(x < y for x, y in zip(seq, seq[1:]))
    

    What does there happens?

    For sequence 1, 2, 3... you take sequences 1, 2, 3... and 2, 3, 4... and zip them together to sequence (1, 2), (2, 3), ... Then you check if statement 'x < y' holds for every pair.

    And this will work for any associative rule you want to check.

    Useful links:

    1. slices in Python

    2. zip in Python docs

    3. all in Python docs

提交回复
热议问题