⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 appendix_a.txt

📁 很详细的Python文字处理教程
💻 TXT
📖 第 1 页 / 共 5 页
字号:
      can be accessed by subscripting and slicing; unlike a
      tuple, list methods and index and slice assignments can
      modify the length and membership of a list object.

      The constructor syntax for a list is surrounding square
      braces.  An empty list may be constructed with no objects
      between the braces; a length-one list can contain simply an
      object name; longer lists separate each element object with
      commas.  Indexing and slices, of course, also use square
      braces, but the syntactic contexts are different in the
      Python grammar (and common sense usually points out the
      difference).  Some examples:

      >>> lst = ['spam', (1,2,3), 'eggs', 3.1415]
      >>> lst[:2]
      ['spam', (1, 2, 3)]

      The function `list()` may also be used to construct a
      list from another sequence type (either a tuple or custom
      sequence type).

      SEE ALSO, [list]

  dict
      A mutable mapping between immutable keys and object values.
      At most one entry in a dict exists for a given key; adding
      the same key to a dictionary a second time overrides the
      previous entry (much as with binding a name in a
      namespace).  Dicts are unordered, and entries are accessed
      either by key as index; by creating lists of contained
      objects using the methods '.keys()', '.values()', and
      '.items()'; or--in recent Python versions--with the
      '.popitem()' method.  All the dict methods generate
      contained objects in an unspecified order.

      The constructor syntax for a dict is surrounding curly
      brackets.  An empty dict may be constructed with no objects
      between the brackets.  Each key/value pair entered into a
      dict is separated by a colon, and successive pairs are
      separated by commas.  For example:

      >>> dct = {1:2, 3.14:(1+2j), 'spam':'eggs'}
      >>> dct['spam']
      'eggs'
      >>> dct['a'] = 'b'    # add item to dict
      >>> dct.items()
      [('a', 'b'), (1, 2), ('spam', 'eggs'), (3.14, (1+2j))]
      >>> dct.popitem()
      ('a', 'b')
      >>> dct
      {1: 2, 'spam': 'eggs', 3.14: (1+2j)}

      In Python 2.2+, the function `dict()` may also be used to
      construct a dict from a sequence of pairs or from a custom
      mapping type.  For example:

      >>> d1 = dict([('a','b'), (1,2), ('spam','eggs')])
      >>> d1
      {'a': 'b', 1: 2, 'spam': 'eggs'}
      >>> d2 = dict(zip([1,2,3],['a','b','c']))
      >>> d2
      {1: 'a', 2: 'b', 3: 'c'}

      SEE ALSO, [dict]

  sets.Set
      Python 2.3+ includes a standard module that implements a
      set datatype.  For earlier Python versions, a number of
      developers have created third-party implementations of
      sets. If you have at least Python 2.2, you can download and
      use the [sets] module from <http://tinyurl.com/2d31> (or
      browse the Python CVS)--you will need to add the definition
      'True,False=1,0' to your local version, though.

      A set is an unordered collection of hashable objects.
      Unlike a list, no object can occur in a set more than once;
      a set resembles a dict that has only keys but no values.
      Sets utilize bitwise and Boolean syntax to perform basic
      set-theoretic operations; a subset test does not have a
      special syntactic form, instead using the '.issubset()' and
      '.issuperset()' methods.   You may also loop through set
      members in an unspecified order.  Some examples illustrate
      the type:

      >>> from sets import Set
      >>> x = Set([1,2,3])
      >>> y = Set((3,4,4,6,6,2)) # init with any seq
      >>> print x, '//', y       # make sure dups removed
      Set([1, 2, 3]) // Set([2, 3, 4, 6])
      >>> print x | y            # union of sets
      Set([1, 2, 3, 4, 6])
      >>> print x & y            # intersection of sets
      Set([2, 3])
      >>> print y-x              # difference of sets
      Set([4, 6])
      >>> print x ^ y            # symmetric difference
      Set([1, 4, 6])

      You can also check membership and iterate over set members:

      >>> 4 in y                 # membership check
      1
      >>> x.issubset(y)          # subset check
      0
      >>> for i in y:
      ...     print i+10,
      ...
      12 13 14 16
      >>> from operator import add
      >>> plus_ten = Set(map(add, y, [10]*len(y)))
      >>> plus_ten
      Set([16, 12, 13, 14])

      `sets.Set` also supports in-place modification of sets;
      `sets.ImmutableSet`, naturally, does not allow
      modification.

      >>> x = Set([1,2,3])
      >>> x |= Set([4,5,6])
      >>> x
      Set([1, 2, 3, 4, 5, 6])
      >>> x &= Set([4,5,6])
      >>> x
      Set([4, 5, 6])
      >>> x ^= Set([4,5])
      >>> x
      Set([6])

  TOPIC -- Compound Types
  --------------------------------------------------------------------

  class instance
      A class instance defines a namespace, but this namespace's
      main purpose is usually to act as a data container  (but a
      container that also knows how to perform actions; i.e., has
      methods).  A class instance (or any namespace) acts very
      much like a dict in terms of creating a mapping between
      names and values.  Attributes of a class instance may be
      set or modified using standard qualified names and may
      also be set within class methods by qualifying with the
      namespace of the first (implicit) method argument,
      conventionally called 'self'.  For example:

      >>> class Klass:
      ...     def setfoo(self, val):
      ...         self.foo = val
      ...
      >>> obj = Klass()
      >>> obj.bar = 'BAR'
      >>> obj.setfoo(['this','that','other'])
      >>> obj.bar, obj.foo
      ('BAR', ['this', 'that', 'other'])
      >>> obj.__dict__
      {'foo': ['this', 'that', 'other'], 'bar': 'BAR'}

      Instance attributes often dereference to other class
      instances, thereby allowing hierarchically organized
      namespace quantification to indicate a data structure.
      Moreover, a number of "magic" methods named with leading
      and trailing double-underscores provide optional syntactic
      conveniences for working with instance data. The most
      common of these magic methods is '.__init__()', which
      initializes an instance (often utilizing arguments).  For
      example:

      >>> class Klass2:
      ...     def __init__(self, *args, **kw):
      ...         self.listargs = args
      ...         for key, val in kw.items():
      ...             setattr(self, key, val)
      ...
      >>> obj = Klass2(1, 2, 3, foo='FOO', bar=Klass2(baz='BAZ'))
      >>> obj.bar.blam = 'BLAM'
      >>> obj.listargs, obj.foo, obj.bar.baz, obj.bar.blam
      ((1, 2, 3), 'FOO', 'BAZ', 'BLAM')

      There are quite a few additional "magic" methods that
      Python classes may define.  Many of these methods let class
      instances behave more like basic datatypes (while still
      maintaining special class behaviors).  For example, the
      '.__str__()' and '.__repr__()' methods control the string
      representation of an instance; the '.__getitem__()' and
      '.__setitem__()' methods allow indexed access to instance
      data (either dict-like named indices, or list-like numbered
      indices); methods like '.__add__()', '.__mul__()',
      '.__pow__()', and '.__abs__()' allow instances to behave in
      number-like ways.  The _Python Reference Manual_ discusses
      magic methods in detail.

      In Python 2.2 and above, you can also let instances behave
      more like basic datatypes by inheriting classes from these
      built-in types.  For example, suppose you need a datatype
      whose "shape" contains both a mutable sequence of elements
      and a '.foo' attribute.  Two ways to define this datatype
      are:

      >>> class FooList(list):        # works only in Python 2.2+
      ...     def __init__(self, lst=[], foo=None):
      ...         list.__init__(self, lst)
      ...         self.foo = foo
      ...
      >>> foolist = FooList([1,2,3], 'FOO')
      >>> foolist[1], foolist.foo
      (2, 'FOO')
      >>> class OldFooList:           # works in older Pythons
      ...     def __init__(self, lst=[], foo=None):
      ...         self._lst, self.foo = lst, foo
      ...     def append(self, item):
      ...         self._lst.append(item)
      ...     def __getitem__(self, item):
      ...         return self._lst[item]
      ...     def __setitem__(self, item, val):
      ...         self._lst[item] = val
      ...     def __delitem__(self, item):
      ...         del self._lst[item]
      ...
      >>> foolst2 = OldFooList([1,2,3], 'FOO')
      >>> foolst2[1], foolst2.foo
      (2, 'FOO')

  If you need more complex datatypes than the basic types, or even
  than an instance whose class has magic methods, often these can
  be constructed by using instances whose attributes are bound in
  link-like fashion to other instances.  Such bindings can be
  constructed according to various topologies, including circular
  ones (such as for modeling graphs).  As a simple example, you
  can construct a binary tree in Python using the following
  node class:

      >>> class Node:
      ...     def __init__(self, left=None, value=None, right=None):
      ...         self.left, self.value, self.right = left, value, right
      ...     def __repr__(self):
      ...         return self.value
      ...
      >>> tree = Node(Node(value="Left Leaf"),
      ...             "Tree Root",
      ...             Node(left=Node(value="RightLeft Leaf"),
      ...                  right=Node(value="RightRight Leaf") ))
      >>> tree,tree.left,tree.left.left,tree.right.left,tree.right.right
      (Tree Root, Left Leaf, None, RightLeft Leaf, RightRight Leaf)

  In practice, you would probably bind intermediate nodes to
  names, in order to allow easy pruning and rearrangement.

  SEE ALSO, [int], [float], [list], [string], [tuple],
  [UserDict], [UserList], [UserString]


SECTION -- Flow Control
--------------------------------------------------------------------

  Depending on how you count it, Python has about a half-dozen flow
  control mechanisms, which is much simpler than most programming
  languages. Fortunately, Python's collection of mechanisms is well
  chosen, with a high--but not obsessively high--degree of
  orthogonality between them.

  From the point of view of this introduction, exception handling
  is mostly one of Python's flow control techniques. In a language
  like Java, an application is probably considered "happy" if it
  does not throw any exceptions at all, but Python programmers find
  exceptions less "exceptional"--a perfectly good design might exit
  a block of code -only- when an exception is raised.

  Two additional aspects of the Python language are not usually
  introduced in terms of flow control, but nonetheless amount to
  such when considered abstractly. Both functional programming
  style operations on lists and Boolean shortcutting are, at the
  heart, flow control constructs.

  TOPIC -- 'if'/'then'/'else' Statements
  --------------------------------------------------------------------

  Choice between alternate code paths is generally performed with
  the 'if' statement and its optional 'elif' and 'else' components.
  An 'if' block is followed by zero or more 'elif' blocks; at the
  end of the compound statement, zero or one 'else' blocks occur.
  An 'if' statement is followed by a Boolean expression and a
  colon. Each 'elif' is likewise followed by a Boolean expression
  and colon. The 'else' statement, if it occurs, has no Boolean
  expression after it, just a colon. Each statement introduces a
  block containing one or more statements (indented on the
  following lines or on the same line, after the colon).

  Every expression in Python has a Boolean value, including every
  bare object name or literal. Any empty container (list, dict,
  tuple) is considered false; an empty string or unicode string is
  false; the number 0 (of any numeric type) is false. As well, an
  instance whose class defines a '.__nonzero__()' or '.__len__()'
  method is false if these methods return a false value. Without
  these special methods, every instance is true. Much of the time,
  Boolean expressions consist of comparisons between objects, where
  comparisons actually evaluate to the canonical objects "0" or
  "1". Comparisons are '<', '>', '==', '>=', '<=', '<>', '!=',
  'is', 'is not', 'in', and 'not in'. Sometimes the unary operator
  'not' precedes such an expression.

  Only one block in an "if/elif/else" compound statement is executed
  during any pass--if multiple conditions hold, the first one that
  evaluates as true is followed. For example:

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -