This is the fourth day of my participation in the November Gwen Challenge. Check out the details: The last Gwen Challenge 2021.
What would you do to get all even cubed from a = [1, 2, 3, 4, 5, 6]?
You might say to me:
list(map(lambda x: x ** 3.filter(lambda x: x % 2= =0, a)))
Copy the code
But with pipe, the third-party library, the code is much cleaner:
from pipe import select, where
list(a | select(lambda x: x ** 3) | where(lambda x: x % 2= =0))
Copy the code
introduce
Like bash, the PIPE library is an implementation of infix syntax in Python. This is an innovative way of using iterators and generators — treating data as a stream and processing and passing it through and through a series of functions. This writing method can greatly avoid nesting between functions, simple and powerful code!
Honestly, looking at this, I already want to refactor all my code… (But of course not)
PIP download:
pip install pipe
Copy the code
The functions that are used
select
– built-inmap
An alternative
Example: Find the difference between the sum of squares of the first 100 natural numbers and the square of the sum. (Project Euler 6 题)
sum(range(101)) * *2 - sum(range(101) | select(lambda x: x ** 2))
Copy the code
where
– built-infilter
An alternative
Example: Calculate all multiples of 3 or 5 up to 1000. (Project Euler 1 题)
sum(range(1000) | where(lambda x: x % 3= =0 or x % 5= =0))
Copy the code
take_while
和 skip_while
–itertools.takewhile
和 itertools.dropwhile
An alternative
Take_while returns the element when the lambda expression is true; skip_while does the opposite.
Example: Find the sum of even numeric terms considering terms in the Fibonacci sequence whose values are not greater than 4000000. (Project Euler 2 题)
def fib(a, b) :.sum(fib(1.2) | where(lambda x: x % 2= =0) | take_while(lambda x: x < 4000000))
Copy the code
chain
— Link groups of iterables
Example:
>>> list([[1.2], [3.4], [5]] | chain)
[1.2.3.4.5]
Copy the code
Chain expands only iterables that contain only iterables:, such as [1, 2, [3]] does not work, raising TypeError.
traverse
Recursively expand iterables
It’s very useful for flattening iterability.
Example:
>>> list([1.2[3]] | traverse)
[1.2.3]
>>> list([[1.2], [[[3], [[4]]], [5]]] | traverse)
[1.2.3.4.5]
Copy the code
dedup
与 uniq
— deduplicate the function
Example:
>>> list([1.1.2.2.3.3.1.2.3] | dedup)
[1.2.3]
>>> list([1.1.2.2.3.3.1.2.3] | dedup(key=lambda n: n % 2))1.2]
Copy the code
Uniq is similar to DedUP, but deduplicates only continuous values.
>>> list([1.1.2.2.3.3.1.2.3] | uniq)
[1.2.3.1.2.3]
>>> list([1.1.2.2.3.3.1.2.3] | uniq(key=lambda n: n % 2))1.2.3.2.3]
Copy the code
Here are just a few examples of some of the more common functions, see the documentation for more.
The next article will take you to dig the source code of this library, bye ~