Teaching Kids Programming: Videos on Data Structures and Algorithms
The chain function from itertools is a useful function that allows you to return an iterator that returns element one by one following the order.
For example:
1 2 3 4 5 | >>> a = [[1, 2, 3], [4, 5, 6], [7, 8]] >>> chain(a) <itertools.chain object at 0x954800> >>> list(chain(a)) 1,2,3,4,5,6,7,8 |
>>> a = [[1, 2, 3], [4, 5, 6], [7, 8]] >>> chain(a) <itertools.chain object at 0x954800> >>> list(chain(a)) 1,2,3,4,5,6,7,8
We can implement such function using the yield syntax (if the given input is a two dimensional array/list):
1 2 3 4 | def chain(a): for i in a: for j in i: yield j |
def chain(a): for i in a: for j in i: yield j
We go through each sub list, and yield each single element.
–EOF (The Ultimate Computing & Technology Blog) —
GD Star Rating
loading...
220 wordsloading...
Last Post: GoLang: Reverse the Bits
Next Post: A Simple Function to Perform Integer/Float Arithmetic Calculation via AWK