A brief analysis of a python iterator example

  • 2020-04-02 14:07:09
  • OfStack

This article illustrates the simple use of python iterators as an example and shares it with you for your reference. Specific analysis is as follows:

A generator expression is an iterator notation used to generate sequence arguments when a function is called

A generator object can be traversed or converted into a list (or data structure such as a tuple), but not slicing (slicing). When the function's only argument is an iterable sequence, you can remove both sides of the generator expression > To write more elegant code:


>>>> sum(i for i in xrange(10))
 45

The sum statement:

The sum (iterable [start])
Sums start and the items of an iterable from left to right and returns the total. Start defaults to 0. The iterable 's items are annoying Numbers, and are not allowed to be strings. Correct way to concatenate a sequence of strings is by calling ". Join (sequence). Note that sum(range(n), m) is equivalent to reduce(operator. Add, range(n), M) To add floating point values with extended precision, see math.fsum().

The parameter is required to pass in an iterable sequence, and we pass in a generator object, which is perfectly implemented.

Note the following code:

The j above is the generator type, and the j below is the list type:


j = (i for i in range(10)) 
print j,type(j) 
print '*'*70 
 
j = [i for i in range(10)] 
print j,type(j) 

Results:


<generator object <genexpr> at 0x01CB1A30> <type 'generator'>
**********************************************************************
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] <type 'list'>

I hope that this article has helped you to learn Python programming.


Related articles: