Python iterator format

Source: Internet
Author: User

Iterators 1. Iterator Overview:

Iterators are a way to access the elements of a collection. The iterator object is accessed from the first element of the collection until all of the elements have been accessed and finished. Iterators can only move forward without going backwards, but that's fine, because people seldom retreat in the middle of an iteration.

1.1 Advantages of using iterators

For primitive data structures that support random access (such as tuple, list), there is no advantage over the index access of the iterator and the classic for loop, but the index value is lost (you can use the built-in function enumerate () to retrieve the index value). But for data structures that cannot be accessed randomly (such as set), iterators are the only way to access elements.

In addition, one of the great advantages of iterators is that they do not require that all elements in the entire iteration be prepared in advance. An iterator computes an element only when it iterates over it, and before or after that, the element may not exist or be destroyed. This feature makes it particularly useful for traversing large or infinite collections, such as several G files, or Fibonacci sequences, and so on.

The greater credit for iterators is the provision of an interface for a unified access collection, which can be accessed using iterators as long as the __iter__ () method object is defined.

There are two basic methods for iterators

Next method: Returns the next element of the iterator
__iter__ method: Returns the Iterator object itself

The following is an example of how to generate Fibonacci numbers to illustrate why iterators

Example code 1

def Fab (max):    while n < Max:    print  b    = b, A + b    = n + 1

Printing with print directly in the function fab (max) causes the reusability of the function to be poor, because Fab returns none. Other functions cannot get the sequence returned by the FAB function.

Example code 2

def Fab (max):   = while n < Max:    l.append (b)    = B, A + b    return L

Code 2 satisfies the need for reusability, but takes up memory space, preferably not.

Example code 3

classFab (object):def __init__(self, max): Self.max=Max SELF.N, SELF.A, self.b= 0, 0, 1def __iter__(self):return SelfdefNext (self):ifSELF.N <Self.max:r=self.b self.a, self.b= self.b, SELF.A +self.b SELF.N= SELF.N + 1returnRRaiseStopiteration ()

Perform

 for inch Fabs (5):  Print key

The Fabs class continuously returns the next number of columns through next (), and memory consumption is always constant

1.2 Using iterators

Use the built-in factory function iter (iterable) to get an iterator object:

>>> LST = range (5)>>> it = iter (LST)>>> it<listiterator Object at 0x01a63110>

The next element can be accessed using the next () method:

>>>lst. __next () 0>>>lst. __next ()1>>>lst. __next ()2>>>lst. __next ()3>>>lst. __next ()4>>>lst. __next ()
Traceback (most recent call last):
  File "<pyshell#35>" , line 1 , in <module>
   it.__ next__ ()
StopIteration

Python handling iterator out of bounds is throwing stopiteration exception

Understanding the Stopiteration, you can use iterators to traverse the

LST = range (5= iter (LST)try:  while  True:    = it.  __next__()    print  valexcept  stopiteration:   Pass

The For statement automatically calls next () to get the element, and also completes the work of checking the stopiteration exception

LST = range (5= iter (LST) for in it:    print(i) 01234

Generator

The function with yield is called the generator (generator) in Python, with several examples (or the generation of Fibonacci sequence descriptions).

You can see that code 3 is far from the code 1 concise, the generator (yield) can keep the code 1 concise, but also maintain the effect of code 3

Example code 4

def Fab (max):   = 0, 0, 1 while   n < Max:    yield  b    = b, A + b    = n = 1

Perform

 for  in Fab (5):  print n

The effect of yield is to turn a function into a generator, and the function with yield is no longer a normal function, and the Python interpreter treats it as a generator.

Yield action in a nutshell is to save the execution state of the function

In a generator, if there is no return, the default execution is done to the function, and if return is encountered, the stopiteration terminate iteration is thrown directly if return is executed during execution.

1 usage of string formatting
%[(name)][flags][width]. [Precision]typecode
    • (name) optional, used to select the specified key
    • Flags are optional, and the values to choose from are:
      • + Right-aligned, positive plus, negative before plus minus;
      • -left-justified; no sign before positive number, plus minus sign before negative number;
      • Spaces are right-justified, plus a positive number before a negative number plus a minus sign;
      • 0 Right alignment, no sign before positive number, minus sign before negative, and 0 padding in blank
    • Width selectable, occupied widths
    • . Precision optional, number of digits retained after the decimal point
    • TypeCode must choose
      • S, gets the return value of the __str__ method of the passed-in object and formats it to the specified location
      • R, gets the return value of the __repr__ method of the passed-in object and formats it to the specified location
      • C, Integer: Converts a number to its Unicode corresponding value, 10 binary range is 0 <= i <= 1114111 (py27 only supports 0-255); character: add character to specified position
      • O, converts an integer to an octal representation and formats it to a specified location
      • X, converts an integer to a hexadecimal representation and formats it to a specified location
      • D, converts an integer, floating-point number to a decimal representation, and formats it to a specified position
      • E, converting integers, floating-point numbers to scientific notation, and formatting them to a specified location (lowercase e)
      • E, converting integers, floating-point numbers into scientific notation, and formatting them to a specified position (uppercase E)
      • F, converts an integer, floating-point number to a floating-point number representation, and formats it to a specified position (the default is 6 digits after the decimal point)
      • F, ibid.
      • G, auto-adjust convert integers, floating-point numbers to floating-point or scientific notation (more than 6 digits in scientific notation), and format them to a specified location (if scientific counts are e;)
      • G, auto-adjust convert integers, floating-point numbers to floating-point or scientific notation (more than 6 digits in scientific notation), and format them to a specified location (if scientific counts are e;)
      • %, when there is a format flag in the string, a percent sign is required

Common formatting formats

TPL ="I am%s"%"Alex"TPL="I am%s age%d"% ("Alex", 18) TPL="I am% (name) s age percent (age) D"% {"name":"Alex"," Age": 18} TPL="percent%.2f"% 99.97623TPL="I am% (PP). 2f"% {"pp": 123.425556,} TPL="I am%.2f percent"% {"pp": 123.425556,}

2. Format mode

[[Fill]align] [Sign] [#][0][width][,][.precision][type]

    • Fill "optional" white space filled with characters
    • Align "optional" alignment (required with width)
        • <, content left justified
        • Content right-aligned (default)
        • =, the content is right-aligned, the symbol is placed to the left of the padding character, and only valid for numeric types. Even: symbol + filler + number
        • ^, content centered
    • Sign "optional" with unsigned numbers
      • +, positive home Plus, minus plus negative;
      • -The plus sign does not change, minus is negative;
      • Spaces, plus spaces, minus signs and negative;
    • # "optional" for binary, octal, hex, if added #, 0b/0o/0x is displayed, otherwise not displayed
    • , "optional" adds a delimiter to the number, such as: 1,000,000
    • width "Optional" format the size of the placeholder
    • . Precision "optional" decimal digits reserved Precision
    • Type "optional" formatting types
        • Parameters passed into the string type
          • s, format string type data
          • Blank, no type specified, default is None, same as S
        • Parameters passed into the integer type
          • B, automatic conversion of 10 binary integers to 2 binary representation and then formatting
          • C, automatic conversion of 10 binary integers to their corresponding Unicode characters
          • d, decimal integer
          • O, the 10 binary integers are automatically converted to 8 binary representation and then formatted;
          • X, automatically converts 10 binary integers to 16 binary representation and then formats (lowercase x)
          • X, automatically converts 10 binary integers to 16 binary representation and then formats (uppercase X)
        • Parameters passed in floating-point or decimal type
          • E, converted to scientific notation (lowercase e), and then formatted;
          • E, converted to scientific notation (capital E), and then formatted;
          • F, converted to floating-point type (6 digits after the default decimal point), and then formatted;
          • F, converted to floating-point type (6 digits after the default decimal point), and then formatted;
          • G, automatically switch between E and F
          • G, automatically switch between E and F
          • %, display percent (default 6 digits after decimal)

Common formatting

TPL ="I am {}, age {}, {}". Format ("Seven", 18,'Alex') TPL="I am {}, age {}, {}". Format (*["Seven", 18,'Alex']) TPL="I am {0}, age {1}, really {0}". Format ("Seven", 18) TPL="I am {0}, age {1}, really {0}". Format (*["Seven", 18]) TPL="I am {name}, age {age}, really {name}". Format (name="Seven", age=18) TPL="I am {name}, age {age}, really {name}". Format (**{"name":"Seven"," Age": 18}) TPL="I am {0[0]}, age {0[1]}, really {0[2]}". format ([1, 2, 3], [11, 22, 33]) TPL="I am {: s}, age {:d}, Money {: F}". Format ("Seven", 18, 88888.1) TPL="I am {: s}, age {:d}". Format (*["Seven", 18]) TPL="I am {name:s}, age {age:d}". Format (name="Seven", age=18) TPL="I am {name:s}, age {age:d}". Format (**{"name":"Seven"," Age": 18}) TPL="numbers: {: b},{:o},{:d},{:x},{:x}, {:%}". Format (15, 15, 15, 15, 15, 15.87623, 2) TPL="numbers: {: b},{:o},{:d},{:x},{:x}, {:%}". Format (15, 15, 15, 15, 15, 15.87623, 2) TPL="numbers: {0:b},{0:o},{0:d},{0:x},{0:x}, {0:%}". Format (15) TPL="numbers: {num:b},{num:o},{num:d},{num:x},{num:x}, {num:%}". Format (NUM=15)

Python iterator format

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.