Pipe is not a python built-in library, if you install Easy_install, you can install it directly, otherwise you need to download it yourself: http://pypi.python.org/pypi/pipe
This library is introduced because it shows us a very new way to use iterators and generators: streams. The pipe sees the iterated data as a stream, similar to linux,pipe using ' | ' The flow of data is passed and a series of "stream processing" functions are defined to accept and process the data flow, and eventually output the data stream again or generalize the data flow to get a result. Let's look at some examples.
The first one, very simple, uses add to sum:
Python
1 2 3 |
>>> from Pipe import * >>> Range (5) | Add 10 |
Mating numbers and the need to use the where, acting like the built-in function filter, filter out eligible elements:
Python
1 2 |
>>> Range (5) | Where (lambda x:x% 2 = = 0) | Add 6 |
Remember the Fibonacci sequence generator we defined? Find all the numbers less than 10000 in the sequence number and need to use take_while, and itertools function with the same name similar function, intercept elements until the condition is not established:
Python
1 2 3 4 5 |
>>> fib = Fibonacci >>> fib () | Where (lambda x:x% 2 = = 0) \ ... | Take_while (lambda x:x < 10000) \ ... | Add 3382 |
You need to apply a function to an element you can use Select, which acts like a built-in function map; you need to get a list that you can use As_list:
Python
1 2 |
>>> fib () | Select (Lambda x:x * * 2) | Take_while (Lambda x:x < 100) | As_list [1, 1, 4, 9, 25, 64] |
More stream processing functions are also included in the pipe. You can even define a stream handler yourself, you just need to define a generator function and add a decorator pipe. A stream handler function that obtains an element until the index does not meet the criteria is defined as follows:
Python
1 2 3 4 5 6 |
>>> @Pipe ... def take_while_idx (iterable, predicate): ... for IDX, x in Enumerate (iterable): ... if predicate (IDX): Yield x ... else:return ... |
Use this stream handler to get the first 10 digits of the FIB:
Python
1 2 |
>>> fib () | Take_while_idx (lambda x:x < 10) | As_list [1, 1, 2, 3, 5, 8, 13, 21, 34, 55] |
More functions are not introduced here, you can view the pipe source files, a total of 600 lines of the file 300 lines is a document, the document contains a large number of examples.
Pipe is very simple to implement, using the pipe decorator, the ordinary generator function (or return the function of the iterator) agent in an implementation of the __ror__ method of ordinary class instances, but this idea is really interesting.
Turn, as to from who is already unknown ...
Interesting library: pipe (like Linux | piping) Library