1. 程式人生 > >python built-in function 學習筆記

python built-in function 學習筆記

part 1: 幾個參考的頁面:

built-in functions:

http://docs.python.org/library/functions.html

python 內建函式:

http://hi.baidu.com/c2cjushi/blog/item/3cb669eed23abb372797916c.html

part 2: 自己的閱讀心得

python 內建的函式列表: 5*16 = 80 Built-in Functions           abs()     divmod()     input()     open()     staticmethod()
all()     enumerate()     int()     ord()     str()
any()     eval()     isinstance()     pow()     sum()
basestring()     execfile()     issubclass()     print()     super()
bin()     file()     iter()     property()     tuple()
bool()     filter()     len()     range()     type()
bytearray()     float()     list()     raw_input()     unichr()
callable()     format()     locals()     reduce()     unicode()
chr()     frozenset()     long()     reload()     vars()
classmethod()     getattr()     map()     repr()     xrange()
cmp()     globals()     max()     reversed()     zip()
compile()     hasattr()     memoryview()     round()     __import__()
complex()     hash()     min()     set()     apply()
delattr()     help()     next()     setattr()     buffer()
dict()     hex()     object()     slice()     coerce()
dir()     id()     oct()     sorted()     intern()
# 這裡共有5列,一列為一組; # 我的原則是: 先自己看,試著寫,遇到問題再去看別人的網頁 1.1  : abs()  去一個數的絕對值: abs(...)
    abs(number) -> number

    Return the absolute value of the argument.
eg: >>> abs(-1)
1
>>>
1.2  all()  判斷iterator 的元素是否都是非空,"一假為假" all(...)
    all(iterable) -> bool

    Return True if bool(x) is True for all values x in the iterable.
1.3 any()  判斷iterator 的元素是否有非空值, "一真為真" 一個關於 all() 和 any() 的例子: >>> tst  = ['a', 'b','c']
>>> all(tst)
True
>>> any(tst)
True
>>> tst2 = ['a', 'b', '']
>>> all(tst2)
False
>>> any(tst2)
True
1.4  basestring()  嚴格來說,basestring 是一個 類。 python 中基本的字串型別
class basestring(object)
|  Type basestring cannot be instantiated; it is the base for str and unicode.
|
|  Data and other attributes defined here:
|
|  __new__ = <built-in method __new__ of type object>
|      T.__new__(S, ...) -> a new object with type S, a subtype of T
This abstract type is the superclass for str and unicode. It cannot be called or instantiated, but it can be used to test whether an object is an instance of str or

unicode.isinstance(obj, basestring) is equivalent to isinstance(obj, (str, unicode)).
一個例子:
>>> isinstance('aa',basestring)
True
>>> isinstance(11,basestring)
False
>>> isinstance(u'jia',basestring)
True

1.5  bin()  返回一個整型或長整型的二進位制表示(以0b開頭) bin(...)
    bin(number) -> string

    Return the binary representation of an integer or long integer.
一個例子: >>> bin(1)
'0b1'
>>> bin(0)
'0b0'
>>> bin(8)
'0b1000'
1.6  bool() 一個類 class bool(int)
|  bool(x) -> bool
|
|  Returns True when the argument x is true, False otherwise.
|  The builtins True and False are the only two instances of the class bool.
|  The class bool is a subclass of the class int, and cannot be subclassed.
|
|  Method resolution order:
|      bool
|      int
|      object
一個例子: >>> bool('2')
True
>>> bool('')
False
>>> bool(1+2>5)
False
>>> bool(1+2<5)
True
1.7  bytearray()  返回一個位元組陣列  # 詳細用法可以研究!!! # todo class bytearray(object)
|  bytearray(iterable_of_ints) -> bytearray.
|  bytearray(string, encoding[, errors]) -> bytearray.
|  bytearray(bytes_or_bytearray) -> mutable copy of bytes_or_bytearray.
|  bytearray(memory_view) -> bytearray.
|
|  Construct an mutable bytearray object from:
|    - an iterable yielding integers in range(256)
|    - a text string encoded using the specified encoding
|    - a bytes or a bytearray object
|    - any object implementing the buffer API.
|
|  bytearray(int) -> bytearray.
|
|  Construct a zero-initialized bytearray of the given length.
|

Return a new array of bytes. The bytearray type is a mutable sequence of integers in the range 0 <= x < 256. It has most of the usual methods of mutable sequences, described in Mutable Sequence Types, as well as most methods that the str type has, see String Methods.
The optional source parameter can be used to initialize the array in a few different ways:

     * If it is a string, you must also give the encoding (and optionally, errors) parameters; bytearray() then converts the string to bytes using str.encode().
     * If it is an integer, the array will have that size and will be initialized with null bytes.
     * If it is an object conforming to the buffer interface, a read-only buffer of the object will be used to initialize the bytes array.
     * If it is an iterable, it must be an iterable of integers in the range 0 <= x < 256, which are used as the initial contents of the array.

Without an argument, an array of size 0 is created
一個例子: >>> bytearray(8)
bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00')
>>> for k in bytearray(8):
...     print k
...
...
0
0
0
0
0
0
0
0
>>> type(k)
<type 'int'>
>>> for k in bytearray('jia'):
...     print k
...
...
106
105
97
1.8  callable()  判斷物件時候可以呼叫; 返回值為true 的物件不一定能call,  返回值為 false 一定不可以呼叫 callable(...)
    callable(object) -> bool

    Return whether the object is callable (i.e., some kind of function).
    Note that classes are callable, as are instances with a __call__() method. Return True if the object argument appears callable, False if not. If this returns true, it is still possible that a call fails, but if it is false, calling object will never succeed. Note that classes are callable (calling a class returns a new instance); class instances are callable if they have a __call__() method.

>>> class Test():
...     def test(self):
...         print ' test method'

>>> callable(Test)
True
>>> callable(Test())
False
>>> tst = Test()
>>> tst.test()
test method
>>> callable(tst)
False

>>> class Test2():
...     def __call__(self):
...         print 'this is call method'

>>> callable(Test2)
True
>>> callable(Test2())
True
>>>
1.9   chr()    顯示數字對應的ASCII嗎 chr(...)
    chr(i) -> character

    Return a string of one character with ordinal i; 0 <= i < 256.
Convert an integer number to a binary string. The result is a valid Python expression. If x is not a Python int object, it has to define an __index__() method that returns an integer.
一個例子: >>> chr(97)
'a'
相比:
>>> ord('a')
97
>>> bin(97)
'0b1100001'
1.10  classmethod()   類似 staticmethod  class classmethod(object)
|  classmethod(function) -> method
|
|  Convert a function to be a class method.
|
|  A class method receives the class as implicit first argument,
|  just like an instance method receives the instance.
|  To declare a class method, use this idiom:
|
|    class C:
|        def f(cls, arg1, arg2, ...): ...
|        f = classmethod(f)
|
|  It can be called either on the class (e.g. C.f()) or on an instance
|  (e.g. C().f()).  The instance is ignored except for its class.
|  If a class method is called for a derived class, the derived class
|  object is passed as the implied first argument.
|
|  Class methods are different than C++ or Java static methods.
|  If you want those, see the staticmethod builtin. 例子請參見 staicmethod() 1.11  cmp()  比較兩個值的大小 cmp(...)     cmp(x, y) -> integer

    Return negative if x<y, zero if x==y, positive if x>y.
Compare the two objects x and y and return an integer according to the outcome. The return value is negative if x < y, zero if x == y and strictly positive if x > y.

一個例子: >>> cmp(1,4)
-1
>>> cmp(5,4)
1
>>> cmp(4,4)
0
>>>
# 其實,專案中的 經緯度點的過濾演算法可以用到這個方法 1.12  compile() compile(...)
    compile(source, filename, mode[, flags[, dont_inherit]]) -> code object

    Compile the source string (a Python module, statement or expression)
    into a code object that can be executed by the exec statement or eval().
    The filename will be used for run-time error messages.
    The mode must be 'exec' to compile a module, 'single' to compile a
    single (interactive) statement, or 'eval' to compile an expression.
    The flags argument, if present, controls which future statements influence
    the compilation of the code.
    The dont_inherit argument, if non-zero, stops the compilation inheriting
    the effects of any future statements in effect in the code calling
    compile; if absent or zero these statements do influence the compilation,
    in addition to any features explicitly specified.
#NOTE: 這個沒調通 1.13  complex()  得到一個複數  class complex(object)
|  complex(real[, imag]) -> complex number
|
|  Create a complex number from a real part and an optional imaginary part.
|  This is equivalent to (real + imag*1j) where imag defaults to 0.

>>> complex(1,2)
(1+2j)
>>> complex(1)
(1+0j)
1.14 delattr()  刪除一個物件的一個屬性 delattr(...)
    delattr(object, name)

    Delete a named attribute on an object; delattr(x, 'y') is equivalent to
    ``del x.y''.
一個例子: classTest():     name ='test'     age =20 defshow(self): print'name is ',self.name ,' sex is ',self.age        a = Test() a.name ='jia' a.show() #delattr(Test, 'name') delattr(a, 'name') #Test().show() printa.name a.show() # 所謂的delattr(object,name). 對於例項來說, 必須是主動給例項的屬性賦值,否則,即使繼承了父類的屬性值,也不可以用 delattr()。 就像程式中,若要使用 delattr(a, 'name'),必須 a.name ='jia' 1.15 dict()  根據傳入的 key=value pairs 生成一個新的 dict class dict(object)
|  dict() -> new empty dictionary
|  dict(mapping) -> new dictionary initialized from a mapping object's
|      (key, value) pairs
|  dict(iterable) -> new dictionary initialized as if via:
|      d = {}
|      for k, v in iterable:
|          d[k] = v
|  dict(**kwargs) -> new dictionary initialized with the name=value pairs
|      in the keyword argument list.  For example:  dict(one=1, two=2)
>>> dict(a = 'tsinghua', b = 'beijin')
{'a': 'tsinghua', 'b': 'beijin'}
1.16 dir() 其實就是看到所選物件可用的屬性 dir(...)
    dir([object]) -> list of strings

    If called without an argument, return the names in the current scope.
    Else, return an alphabetized list of names comprising (some of) the attributes
    of the given object, and of attributes reachable from it.
    If the object supplies a method named __dir__, it will be used; otherwise
    the default dir() logic is used and returns:
      for a module object: the module's attributes.
      for a class object:  its attributes, and recursively the attributes
        of its bases.
      for any other object: its attributes, its class's attributes, and
        recursively the attributes of its class's base classes.
>>> a = 'jia'
>>> b = dir(a)
>>> b
['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_formatter_field_name_split', '_formatter_parser', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
>>> c = dir()
>>> c
['__builtins__', '__doc__', '__name__', '__package__', 'a', 'b']

2.1 : divmod()  對一個表示式進行求餘數和商數的計算: divmod(...)
    divmod(x, y) -> (div, mod)

    Return the tuple ((x-x%y)/y, x%y).  Invariant: div*y + mod == x.
eg:
>>> divmod(10,3)
(3, 1)
>>> a, b = divmod(10, 3)
>>> a
3
>>> b
1
>>>
2.2 enumerate()   # 對傳入的迭代物件進行迭代,返回迭代物件中的元素和相應的索引。 class enumerate(object)
|  enumerate(iterable[, start]) -> iterator for index, value of iterable
|
|  Return an enumerate object.  iterable must be another object that supports
|  iteration.  The enumerate object yields pairs containing a count (from
|  start, which defaults to zero) and a value yielded by the iterable argument.
|  enumerate is useful for obtaining an indexed list:
|      (0, seq[0]), (1, seq[1]), (2, seq[2]), ...
|
|  Methods defined here:
|
|  __getattribute__(...)
|      x.__getattribute__('name') <==> x.name
|
|  __iter__(...)
|      x.__iter__() <==> iter(x)
|
|  next(...)
|      x.next() -> the next value, or raise StopIteration
|
|  ----------------------------------------------------------------------
|  Data and other attributes defined here:
|
|  __new__ = <built-in method __new__ of type object>
|      T.__new__(S, ...) -> a new object with type S, a subtype of T
>>> a = 'jia' >>> for k,v in enumerate(a): ...     print k, v
...
0 j
1 i
2 a
>>> for k,v in enumerate(a,2):
...     print k, v
...
2 j
3 i
4 a
>>>
2.3 eval()  # 執行一個指定的字串; 求值,有返回結果 eval(...)
    eval(source[, globals[, locals]]) -> value

    Evaluate the source in the context of globals and locals.
    The source may be a string representing a Python expression
    or a code object as returned by compile().
    The globals must be a dictionary and locals can be any mapping,
    defaulting to the current globals and locals.
    If only globals is given, locals defaults to it.
>>> eval('5-4') 1
>>> cal = "7-8+11"
>>> eval(cal)
10
2.4 execfile() # 類似exec, 只是引數來源於一個file execfile(...)
    execfile(filename[, globals[, locals]])

    Read and execute a Python script from a file.
    The globals and locals are dictionaries, defaulting to the current
    globals and locals.  If only globals is given, locals defaults to it.
# 呵呵,這有點像 shell 的輸入重定向 >>> exec("print '11'")
11
# 將上面的“print 11"  寫在 ex.py 檔案中 
>>> execfile("ex.py")
11
2.5 file()   # 關於檔案操作的一些 class file(object)
|  file(name[, mode[, buffering]]) -> file object
|
|  Open a file.  The mode can be 'r', 'w' or 'a' for reading (default),
|  writing or appending.  The file will be created if it doesn't exist
|  when opened for writing or appending; it will be truncated when
|  opened for writing.  Add a 'b' to the mode for binary files.
|  Add a '+' to the mode to allow simultaneous reading and writing.
|  If the buffering argument is given, 0 means unbuffered, 1 means line
|  buffered, and larger numbers specify the buffer size.  The preferred way
|  to open a file is with the builtin open() function.
|  Add a 'U' to mode to open the file for input with universal newline
|  support.  Any line ending in the input file will be seen as a '\n'
|  in Python.  Also, a file so opened gains the attribute 'newlines';
|  the value for this attribute is one of None (no newline read yet),
|  '\r', '\n', '\r\n' or a tuple containing all the newline types seen.
|
|  'U' cannot be combined with 'w' or '+' mode.
# 這裡的file() 返回一個檔案物件,  # TODO: 關於檔案的操作其實有很多內容,有時間可以新增進來 2.6 filter()  對傳入的列表做過濾,過濾條件為function. filter(...)
    filter(function or None, sequence) -> list, tuple, or string

    Return those items of sequence for which function(item) is true.  If
    function is None, return the items that are true.  If sequence is a tuple
    or string, return the same type, else return a list.
>>> def test(value):
...     return value>10
...
>>> a = [1,2,3,4,5,6,7,8,9,10,11,12,13]
>>> filter(test,a)
[11, 12, 13]
2.7  float()  構建一個浮點型的物件 class float(object)
|  float(x) -> floating point number
|
|  Convert a string or number to a floating point number, if possible.
|
|  Methods defined here:
|
|  __abs__(...)
|      x.__abs__() <==> abs(x)
|
|  __add__(...)
|      x.__add__(y) <==> x+y
>>> float(1)
1.0
>>> float(10)
10.0
2.8  format() format(...)
    format(value[, format_spec]) -> string

    Returns value.__format__(format_spec)
    format_spec defaults to ""
>>> format('jia','')
'jia'
>>> format('jia')
'jia'
# 坦率的說,這個不是太熟悉,感覺沒什麼用 2.9 frozenset() class frozenset(object)
|  frozenset() -> empty frozenset object
|  frozenset(iterable) -> frozenset object
|
|  Build an immutable unordered collection of unique elements.
|
|  Methods defined here:
|
|  __and__(...)
|      x.__and__(y) <==> x&y
|
|  __cmp__(...)
|      x.__cmp__(y) <==> cmp(x,y) # 簡單來說就是構建一個無序的set  >>> a = [1,2,3,3,3,]
>>> frozenset(a)
frozenset([1, 2, 3])
>>> b = frozenset(a)
>>> b
frozenset([1, 2, 3])
>>> for k in b:
...     print k
...
1
2
3
2.10 getattr()  獲取一個物件的屬性 getattr(...)
    getattr(object, name[, default]) -> value

    Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.
    When a default argument is given, it is returned when the attribute doesn't
    exist; without it, an exception is raised in that case. >>> class person():
...     name = 'jia'
...
>>> p = person()
>>> p.name
'jia'
>>> getattr(p,'name')
'jia'
2.11  globals()   返回一個當前作用域的key,value pairs # 其實,可以比較locals(), vars(), locals() 一起學習 globals(...)
    globals() -> dictionary

    Return the dictionary containing the current scope's global variables.
>>> globals()
{'a': [1, 2, 3, 3, 3], 'b': frozenset([1, 2, 3]), '__builtins__': <module '__builtin__' (built-in)>, 'k': 3, '__package__': None, 'test': <function test at 0x7f0fe09f0500>, '__name__': '__main__', '__doc__': None}
>>> vars()
{'a': [1, 2, 3, 3, 3], 'b': frozenset([1, 2, 3]), '__builtins__': <module '__builtin__' (built-in)>, 'k': 3, '__package__': None, 'test': <function test at 0x7f0fe09f0500>, '__name__': '__main__', '__doc__': None}
>>> locals()
{'a': [1, 2, 3, 3, 3], 'b': frozenset([1, 2, 3]), '__builtins__': <module '__builtin__' (built-in)>, 'k': 3, '__package__': None, 'test': <function test at 0x7f0fe09f0500>, '__name__': '__main__', '__doc__': None}
2.12  hasattr()  判斷一個物件中是否有某個屬性 hasattr(...)
    hasattr(object, name) -> bool

    Return whether the object has an attribute with the given name.
    (This is done by calling getattr(object, name) and catching exceptions.)
>>> hasattr(p,'name')
True
# getattr, hasattr 的區別。對於一個不存在的屬性。getattr 是會報異常的。hasattr() 不會。 我疑心底層實現中,改成: 如果property不存在,getattr 直接返回None 會更好一些。(只是個人猜測!) >>> getattr(p,'names')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: person instance has no attribute 'names'
>>> hasattr(p,'names')
False
2.13 hash()  得到一個物件的雜湊值。 ”值相同的物件擁有相同的hash 值,hash 值相同,物件也大多數相同“ hash(...)
    hash(object) -> integer

    Return a hash value for the object.  Two objects with the same value have
    the same hash value.  The reverse is not necessarily true, but likely.
>>> hash(b)
-7699079583225461316
>>> hash(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
2.14  help()  應該說是在命令列最常用的方法了,比如>>help(help), >>help(hash) class _Helper(__builtin__.object)
|  Define the built-in 'help'.
|  This is a wrapper around pydoc.help (with a twist).
|
|  Methods defined here:
|
|  __call__(self, *args, **kwds)
|
|  __repr__(self)
|
|  ----------------------------------------------------------------------
|  Data descriptors defined here:
|
|  __dict__
|      dictionary for instance variables (if defined)
|
|  __weakref__
|      list of weak references to the object (if defined)
讀取內部的 __doc__, 自己定義的一些函式也會被呼叫!! >>> def test():
...     """ this is a doc test"""
... >>> test.__doc__
' this is a doc test'
>>> help(test)
2.15 hex()   將一個十進位制的數轉換為16進位制 hex(...)
    hex(number) -> string

    Return the hexadecimal representation of an integer or long integer.
>>> hex(20)
'0x14'
>>> hex(20L)
'0x14L'
>>> hex(20l)
'0x14L'
>>> a = hex(20l)
>>> int(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '0x14L'
>>> long(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for long() with base 10: '0x14L'
# 其實我一直想知道,把一個long 型轉為16進位制有何用! 2.16 id() 返回一個物件的唯一id id(...)
    id(object) -> integer

    Return the identity of an object.  This is guaranteed to be unique among
    simultaneously existing objects.  (Hint: it's the object's memory address.)
>>> id(p)
140165793784968
>>> id([1,2,])
25908792
>>> id([1,2,3])
25908792
>>> id([1,2,3,4])
25908792
>>> a = [1,2]
>>> id(a)
25908792
>>> b=[1,2,3]
>>> id(b)
25912240
>>> a.append(5)
>>> a
[1, 2, 5]
>>> id(a)
25908792
>>> id([1,23,5])
140165793639096
>>> id([1,2,5])
140165793639096
>>> id([1,2,5,6])
140165793639096
>>> id([1,2,5,6,7]) >>> id([7])
140165793639096
>>> id([])
140165793639096
140165793639096 # 基本上還是可信的,有人可以解釋一下id(list) 的返回值為何相同嗎? 3.1  input()  接收螢幕的一個輸入值 
input(...)
    input([prompt]) -> value

    Equivalent to eval(raw_input(prompt)).
eg: >>> input('please input your age: ')
please input you age: 29
29
>>> raw_input('please input your age: ')
please input your age: 12
'12'
3.2 int()  得到一個interger 物件 class int(object)
|  int(x[, base]) -> integer
|
|  Convert a string or number to an integer, if possible.  A floating point
|  argument will be truncated towards zero (this does not include a string
|  representation of a floating point number!)  When converting a string, use
|  the optional base.  It is an error to supply a base when converting a
|  non-string.  If base is zero, the proper base is guessed based on the
|  string content.  If the argument is outside the integer range a
|  long object will be returned instead.
|
|  Methods defined here:
|
|  __abs__(...)
|      x.__abs__() <==> abs(x)
|
|  __add__(...)
#todo >>> int(-1)
-1
>>> int("12")
12
>>> int("12",16)
18
>>> int("12",8)
10
>>>
3.3  isinstance() 判斷一個物件是否屬於某一個類 isinstance(...)
    isinstance(object, class-or-type-or-tuple) -> bool

    Return whether an object is an instance of a class or of a subclass thereof.
    With a type as second argument, return whether that is the object's type.
    The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for
    isinstance(x, A) or isinstance(x, B) or ... (etc.).
一個簡單的方法:  AKV, 對一個i物件進行多種例項判斷的快捷方式: isinstance(x,(A,B,C)) 一個舉例: >>> a = [1,2,3]
>>> b = (1,2,3)
>>> if isinstance(a,list):
...     print 'list'
... elif isinstance(b,tuple):
...     print 'b tuple'
... elif isinstance(a,tuple):
...     print 'a tuple'
... elif isinstance(b,list):
...     print 'b tuple'
...
list
>>> type(a)
<type 'list'>
>>> type(b)
<type 'tuple'>
>>>
3.4  issubclass() 判斷一個類是否是另一個類的子類 issubclass(...)
    issubclass(C, B) -> bool

    Return whether class C is a subclass (i.e., a derived class) of class B.
    When using a tuple as the second argument issubclass(X, (A, B, ...)),
    is a shortcut for issubclass(X, A) or issubclass(X, B) or ... (etc.).
# 這裡和isinstance(x,(A,B,C)) 一樣,也可以一次判斷多個
>>> class A():
...     def test(self):
...             print 'this is A'
...
>>> class B(A):
...     def test(self):
...             print 'this is B'
... >>> issubclass(B,A)
True
3.5 iter()   iter(...)
    iter(collection) -> iterator
    iter(callable, sentinel) -> iterator

    Get an iterator from an object.  In the first form, the argument must
    supply its own iterator, or be a sequence.
    In the second form, the callable is called until it returns the sentinel.
# 第一種方法: collection 必須支援__iter_(), __getitem__() 方法,否則丟擲TypeError 異常 >>> a = iter([1,2,3])
>>> a
<listiterator object at 0x7fc78b770850>
>>> for k in a:
...     print k
...
1
2
3
這麼看來, 有了enumerate, 完全可以不用iter() 了。 # 第二種方法看不太明白! 第二種方法特別適合開啟一個檔案,一行一行處理文字,直到遇到特定的行。 # 將幾行文字寫入 bbbb.txt 檔案。 >>> with open("bbbb.txt") as fp:
...     for line in iter(fp.readline, 'stop'):
...             print line
...
     1  1

     2  2

     3  3

     4  4

     5  5

     6  6

     7  7

     8  8

     9  9

stop

# 參考別人的例子寫了一個, 和期望的不一樣, 讀到 'stop' 行之後, 還繼續往下讀!!?? #  TODO 3.6 len()  返回一個序列的元素的個數 len(...)
    len(object) -> integer

    Return the number of items of a sequence or mapping.
>>> len('jia')
3
>>> len([1,2,3])
3
3.7 list() class list(object)
|  list() -> new empty list
|  list(iterable) -> new list initialized from iterable's items
|
|  Methods defined here:
|
|  __add__(...)
|      x.__add__(y) <==> x+y
|
|  __contains__(...)
|      x.__contains__(y) <==> y in x
# 通過一個可迭代的物件,得到其中元素說組成的列表。 >>> list('jia')
['j', 'i', 'a']
>>> list([1,2,3])
[1, 2, 3]
>>> list((1,2,3))
[1, 2, 3]
>>> list({'a':1,'b':2,'c':3})
['a', 'c', 'b']
# 讓我有點驚訝的是 對dict 的迭代,這裡竟然也可以成功。,返回一個key 的列表。很顯然,如果要得到一個dict 的列表,可以不使用這個!! 3.8 locals() locals(...)
    locals() -> dictionary

    Update and return a dictionary containing the current scope's local variables.
# 具體參考之前的globals(), 返回一個當前作用域的key-value pairs 3.9 long() class long(object)
|  long(x[, base]) -> integer
|
|  Convert a string or number to a long integer, if possible.  A floating
|  point argument will be truncated towards zero (this does not include a
|  string representation of a floating point number!)  When converting a
|  string, use the optional base.  It is an error to supply a base when
|  converting a non-string.
|
|  Methods defined here:
|
|  __abs__(...)
|      x.__abs__() <==> abs(x)
|
|  __add__(...)
|      x.__add__(y) <==> x+y
返回一個長整型的資料。 3.10 map()  對一個序列中的每個元素進行function  操作。 map(...)
    map(function, sequence[, sequence, ...]) -> list

    Return a list of the results of applying the function to the items of
    the argument sequence(s).  If more than one sequence is given, the
    function is called with an argument list consisting of the corresponding
    item of each sequence, substituting None for missing values when not all
    sequences have the same length.  If the function is None, return a list of
    the items of the sequence (or a list of tuples if more than one sequence).
# 可以參看 filter(function, sequence). filter 是對sequence中的每個元素呼叫function,如果返回為false, 該元素就不會返回。 # map 是對每個元素都執行function, function 的返回結果作為新的引數被輸出。 >>> def add_5(value):
...     return value+5
...
>>> map(add_5,[1,2,3,4])
[6, 7, 8, 9]
3.11 max() max(...)
    max(iterable[, key=func]) -> value
    max(a, b, c, ...[, key=func]) -> value

    With a single iterable argument, return its largest item.
    With two or more arguments, return the largest argument.
# 這裡的預設引數key 可以調研。 >>> max([1,2,3,4,5,6,7,45,2,43,])
45
>>> max(['jia','luo','guo'])
'luo'
# 一直想傳遞一個引數 key = function, 不知道改如何傳!!? deftest(a,b):     aa = a[0]     bb = b[0] iford(aa) > ord(bb): returnTrue print  max([1,2,3]) lst = ['jia','luo','guo'] print   max(*lst, key=test) # 現在明白了。 定義的函式func, 不是用來實現比較的邏輯的。是為了對其中的每一個元素做比較的 deftest(a): returna*2 deftest2(a): returna%3 print  max([1,2,3,4],key=test2) lst = ['jia','luo','guo'] print   max(*lst, key=test) 3.12 memoryview() # 在命令列中竟然找不到這個方法,在其他人的部落格中也沒有這個方法,再確認!!!#TODO
3.13  min() min(...)
    min(iterable[, key=func]) -> value
    min(a, b, c, ...[, key=func]) -> value

    With a single iterable argument, return its smallest item.
    With two or more arguments, return the smallest argument.
# 具體參考 max()  3.14  next() next(...)
    next(iterator[, default])

    Return the next item from the iterator. If default is given and the iterator
    is exhausted, it is returned instead of raising StopIteration.
>>> a = [1,2,3,4]
>>> b = iter(a)
>>> next(b)
1
>>> next(b)
2
>>> next(b)
3
>>> next(b)
4
>>> next(b)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration

# 對於那些固定值得引數時可以的。 3.15 object() class object
|  The most base type
# 最基本的類。  在定義類的時候 # 最基本的方法由C底層實現,看不到原始碼! 3.16  oct() oct(...)
    oct(number) -> string

    Return the octal representation of an integer or long integer.
# 類似hex(), 返回一個數的八進位制表示! >>> oct(1)
'01'
>>> oct(2)
'02'
>>> oct(122)
'0172'
>>> oct(16)
'020'
>>> hex(16)
'0x10'
4.1 open()  開啟一個檔案, open(...)
    open(name[, mode[, buffering]]) -> file object

    Open a file using the file() type, returns a file object.  This is the
    preferred way to open a file.
# 建立一個檔案 a.txt, 輸入一段文字
>>> f = open('a.txt')
>>> f.readline()
'hello, world!\n'
>>>
4.2 ord()  彷彿單位元組字元對應的ascii 碼 ord(...)
    ord(c) -> integer

    Return the integer ordinal of a one-character string.
>>> ord('a')
97
>>> ord('\x20')
32
>>> ord('12')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: ord() expected a character, but string of length 2 found
4.3 pow() pow(...)
    pow(x, y[, z]) -> number

    With two arguments, equivalent to x**y.  With three arguments,
    equivalent to (x**y) % z, but may be more efficient (e.g. for longs).
# 求冪運算 >>> 2**4
16
>>> pow(2,4)
16
>>> pow(2,4,3)
1
>>> (2**4) % 3
1
4.4  print() 這裡竟然help不可以,!!?? 4.5 property()
class property(object)
|  property(fget=None, fset=None, fdel=None, doc=None) -> property attribute
|
|  fget is a function to be used for getting an attribute value, and likewise
|  fset is a function for setting, and fdel a function for del'ing, an
|  attribute.  Typical use is to define a managed attribute x:
|  class C(object):
|      def getx(self): return self._x
|      def setx(self, value): self._x = value
|      def delx(self): del self._x
|      x = property(getx, setx, delx, "I'm the 'x' property.")
|
|  Decorators make defining new properties or modifying existing ones easy:
|  class C(object):
|      @property
|      def x(self): return self._x
|      @x.setter
|      def x(self, value): self._x = value
|      @x.deleter
|      def x(self): del self._x
|
|  Methods defined here:
|
|  __delete__(...)
|      descr.__delete__(obj)
|
|  __get__(...)
|      descr.__get__(obj[, type]) -> value
# property 的確是一個值得研究的方法。 最常見的應用就是 在一個方法前新增 @property, 使得方法的呼叫就像屬性一樣來使用。(其實在呼叫的時候, 方法還是會依次執行的) 4.6 range() range(...)
    range([start,] stop[, step]) -> list of integers


    Return a list containing an arithmetic progression of integers.
    range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0.
    When step is given, it specifies the increment (or decrement).
    For example, range(4) returns [0, 1, 2, 3].  The end point is omitted!
    These are exactly the valid indices for a list of 4 elements.
# 獲取一個序列,逐漸被xrange()替代 4.7 raw_input() raw_input(...)     raw_input([prompt]) -> string

    Read a string from standard input.  The trailing newline is stripped.
    If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.
    On Unix, GNU readline is used if enabled.  The prompt string, if given,
    is printed without a trailing newline before reading.

# 確切的來說,這個只有在命令列會使用,接受一個命令列輸入
>>> raw_input('please input a number: ')
please input a number: 12
'12'
>>>
# 在程式中可以接受一些命令列中的輸入: # tip2: define a list of switch        SWITCHES = ['realtime','remotelisten','remoteonoff','enterexitbound', 'removebound','upload_data','login','logout','active_test', 'whitelist','scheduleset','scheduleremove','schedulequery','scheduleonoff'] defusage(): print'please input oneitermof the follows:' forswitchinSWITCHES: printswitch      defmain():    whileTrue:         switch = raw_input("Input your command: ") ifswitchnot